简体   繁体   English

使用反射,如何将值设置为结构字段(指针)

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

I try to set value to a struct field (pointer field) by reflect, but failed. 我尝试通过反射将值设置为结构字段(指针字段),但失败了。

  1. I get the name of a struct field, so use FieldByName to get the field 我得到一个结构字段的名称,所以使用FieldByName来获取字段
  2. The field is a pointer. 该字段是一个指针。
  3. I try to use FieldByName().Set FieldByName().SetPointer to set value. 我尝试使用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)
}

First code: =======> ./test.go:14:50: cannot use a (type *int) as type reflect.Value in argument to reflect.ValueOf(t).FieldByName("b").Set ./test.go:14:50: reflect.ValueOf(t).FieldByName("b").Set(a) used as value 第一个代码:=======> ./test.go:14:50:不能使用(类型* int)作为类型reflect.Value的实参中的reflect.ValueOf(t).FieldByName(“ b”) .Set ./test.go:14:50:Reflection.ValueOf(t).FieldByName(“ b”)。Set(a)用作值

Second code: =======> ./test.go:14:57: cannot use a (type *int) as type unsafe.Pointer in argument to reflect.ValueOf(t).FieldByName("b").SetPointer ./test.go:14:57: reflect.ValueOf(t).FieldByName("b").SetPointer(a) used as value 第二个代码:=======> ./test.go:14:57:不能使用(类型* int)作为unsafe类型。参数中的指针要反映.ValueOf(t).FieldByName(“ b”) .SetPointer ./test.go:14:57:Reflection.ValueOf(t).FieldByName(“ b”)。SetPointer(a)用作值

I want to use reflect to make the pointer field (name "b") alloced a space and set a value. 我想使用反射使指针字段(名称“ 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)
}

Playground https://play.golang.org/p/gZt0ahTZMIi 游乐场https://play.golang.org/p/gZt0ahTZMIi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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