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

时间:2019-08-30 03:57:30

标签: go reflection

我希望下面的Set方法将传入的APtr结构的B字段设置为按值传递的值,即没有指针间接作用。

要通过反射进行工作,我可能必须将该值复制到我有地址的新位置?无论哪种方式,我如何才能使它正常工作?我有一个适用于非指针值的工作版本。

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

1 个答案:

答案 0 :(得分:2)

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_rKbgO9

https://play.golang.org/p/B6vOONQ-RXO(紧凑)