简体   繁体   中英

How to copy a non-pointer value to a pointer indirected value via reflection

I want the Set method below to set the APtr field of a passed in B struct to a value that gets passed in by value, ie without a pointer indirection.

For that to work via go reflection, I will probably have to copy that value to a new location that I have the address of? Either way, how can I get this to work? What I have is a working version for non-pointers values.

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
}

Playground: https://play.golang.org/p/6tcmbXxBcIm

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 (compact)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM