簡體   English   中英

如何通過反射將非指針值復制到指針間接值

[英]How to copy a non-pointer value to a pointer indirected value via reflection

我希望下面的Set方法將傳入的B結構的APtr字段設置為通過值傳入的值,即沒有指針間接傳遞。

為了通過反射實現該功能,我可能必須將該值復制到我擁有地址的新位置? 無論哪種方式,我如何才能使它正常工作? 我有一個非指針值的工作版本。

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

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 (緊湊)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM