簡體   English   中英

使用反射,如何將值設置為結構字段(指針)

[英]Using reflect, how to set value to a struct field (pointer)

我嘗試通過反射將值設置為結構字段(指針字段),但失敗了。

  1. 我得到一個結構字段的名稱,所以使用FieldByName來獲取字段
  2. 該字段是一個指針。
  3. 我嘗試使用FieldByName()。設置FieldByName()。SetPointer來設置值。
type t struct {
    b *int
}

func main() {
    t := new(ts)
    a := new(int)
    ss := reflect.ValueOf(t).FieldByName("b").Set(a)
}
type t struct {
    b *int
}

func main() {
    t := new(ts)
    a := new(int)
    ss := reflect.ValueOf(t).FieldByName("b").SetPointer(a)
}

第一個代碼:=======> ./test.go:14:50:不能使用(類型* int)作為類型reflect.Value的實參中的reflect.ValueOf(t).FieldByName(“ b”) .Set ./test.go:14:50:Reflection.ValueOf(t).FieldByName(“ b”)。Set(a)用作值

第二個代碼:=======> ./test.go:14:57:不能使用(類型* int)作為unsafe類型。參數中的指針要反映.ValueOf(t).FieldByName(“ b”) .SetPointer ./test.go:14:57:Reflection.ValueOf(t).FieldByName(“ b”)。SetPointer(a)用作值

我想使用反射使指針字段(名稱“ b”)分配一個空間並設置一個值。

type ts struct {
    B *int    //field must be exported
}

func main() {
    var t ts
    foo := 5
    a := &foo
    //Use Elem() to indirect through the pointer and get struct field
    //Use reflect.ValueOf(a) to satisfy Set() signature
    reflect.ValueOf(&t).Elem().FieldByName("B").Set(reflect.ValueOf(a))
    fmt.Println(*t.B)
}

游樂場https://play.golang.org/p/gZt0ahTZMIi

暫無
暫無

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

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