亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

Go
小唯快跑啊 2023-07-17 16:24:24
我希望下面的方法將傳入結構的字段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
查看完整描述

1 回答

?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

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


查看完整回答
反對 回復 2023-07-17
  • 1 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號