[Go] golang通过反射获取和设置结构体字段的值 →→→→→进入此内容的聊天室

来自 , 2021-04-02, 写在 Go, 查看 132 次.
URL http://www.code666.cn/view/60ce3672
  1.    type MyStruct struct {
  2.         N int
  3.     }
  4.     n := MyStruct{ 1 }
  5.  
  6.     // get
  7.     immutable := reflect.ValueOf(n)
  8.     val := immutable.FieldByName("N").Int()
  9.     fmt.Printf("N=%d\n", val) // prints 1
  10.  
  11.     // set
  12.     mutable := reflect.ValueOf(&n).Elem()
  13.     mutable.FieldByName("N").SetInt(7)
  14.     fmt.Printf("N=%d\n", n.N) // prints 7
  15. //go/7719

回复 "golang通过反射获取和设置结构体字段的值"

这儿你可以回复上面这条便签

captcha