如何通过反射将非指针值复制到指针间接值

我希望下面的方法将传入结构的字段Set设置为按值传入的值,即没有指针间接寻址。APtrB


为了通过 go 反射工作,我可能必须将该值复制到我有地址的新位置?不管怎样,我怎样才能让它发挥作用?我拥有的是非指针值的工作版本。


type A struct {

    AnInt int

}


type B struct {

    AnA   A

    APtr *A

}


func Set(strukt interface{}, fieldName string, newFieldValue interface{}) {

    struktValueElem := reflect.ValueOf(strukt).Elem()

    field := struktValueElem.FieldByName(fieldName)

    newFieldValueValue := reflect.ValueOf(newFieldValue)

    if field.Kind() == reflect.Ptr {

        // ?? implement me

    } else { // not a pointer? more straightforward:

        field.Set(newFieldValueValue)

    }

}


func main() {

    aB := B{}

    anA := A{4}

    Set(&aB, "AnA", anA) // works

    Set(&aB, "APtr", anA) // implement me

}

游乐场:https://play.golang.org/p/6tcmbXxBcIm


小唯快跑啊
浏览 78回答 1
1回答

Smart猫小萌

func Set(strukt interface{}, fieldName string, newFieldValue interface{}) {    struktValueElem := reflect.ValueOf(strukt).Elem()    field := struktValueElem.FieldByName(fieldName)    newFieldValueValue := reflect.ValueOf(newFieldValue)    if field.Kind() == reflect.Ptr {        rt := field.Type() // type *A        rt = rt.Elem()     // type A        rv := reflect.New(rt) // value *A        el := rv.Elem()       // value A (addressable)        el.Set(newFieldValueValue) // el is addressable and has the same type as newFieldValueValue (A), Set can be used        field.Set(rv)              // field is addressable and has the same type as rv (*A), Set can be used    } else { // not a pointer? more straightforward:        field.Set(newFieldValueValue)    }}https://play.golang.org/p/jgEK_rKbgO9https://play.golang.org/p/B6vOONQ-RXO(紧凑)
打开App,查看更多内容
随时随地看视频慕课网APP