Golang 使用reflect 更改struct内容

代码如下:

type MyStruct struct {
    N int
}
n := MyStruct{ 1 }
 
// get
immutable := reflect.ValueOf(n)
val := immutable.FieldByName("N").Int()
fmt.Printf("N=%d\n", val) // prints 1
 
// set
mutable := reflect.ValueOf(&n).Elem()
mutable.FieldByName("N").SetInt(7)
fmt.Printf("N=%d\n", n.N) // prints 7

http://golang-examples.tumblr.com/post/44089080167/get-set-a-field-value-of-a-struct-using-reflection

你可能感兴趣的:(goLang)