请教 Go 用反射修改结构体的值的问题
資深大佬 : jonathanchoo 9
如果是普通的结构体,遍历 numField 根据 Field(i).Name 修改就可以了
但是如果遇到嵌套结构体怎么办
例如
type A struct { field1 string ... B } type B struct { field2 string }
如何修改修改 field2 的值呢?
大佬有話說 (2)
如果是普通的结构体,遍历 numField 根据 Field(i).Name 修改就可以了
但是如果遇到嵌套结构体怎么办
例如
type A struct { field1 string ... B } type B struct { field2 string }
如何修改修改 field2 的值呢?
type A struct {
Field1 string
*B
}
type B struct {
Field2 string
}
func main() {
a := A{B: &B{Field2: “123”}}
println(a.B.Field2)
v := reflect.ValueOf(&a)
v.Elem().FieldByName(“B”).Elem().FieldByName(“Field2”).Set(reflect.ValueOf(“456”))
println(a.B.Field2)
}
https://play.golang.org/p/dJ5sWunyVby