I try to set value to a struct field (pointer field) by reflect, but failed.
- I get the name of a struct field, so use FieldByName to get the field
- The field is a pointer.
- I try to use FieldByName().Set FieldByName().SetPointer to set value.
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
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
I want to use reflect to make the pointer field (name "b") alloced a space and set a value.