Go语言反射修改变量教程
在 中,通过 我们可以修改 的值。在修改变量的值之前,最好使用 方法获取是否可以修改该变量的值。
通过反射修改变量的值,有两种方法,一种是使用 Set 方法,一种是使用 SetXXX() 方法,比如 SetString()、SetInt() 等。
Go语言反射修改变量
语法
reflect.ValueOf(&x).Elem().Set()
说明
reflect.ValueOf
其中,Set 方法接受的 是一个 reflect.ValueOf 的 。
Go语言反射修改变量
语法
reflect.ValueOf(&x).Elem().SetXXX()
说明
reflect.ValueOf
案例
Go语言反射修改变量
通过反射的 SetXXX 方法修改变量的值
package main import ( "fmt" "reflect" ) func main() { fmt.Println("嗨客网(www.haicoder.net)") var x = 1024 var str = "HaiCoder" xValue := reflect.ValueOf(&x).Elem() strValue := reflect.ValueOf(&str).Elem() if xValue.CanSet(){ xValue.SetInt(10240) fmt.Println("New xValue =", xValue) } if strValue.CanSet(){ strValue.SetString("haicoder") fmt.Println("New strValue =", strValue) } }
程序运行后,控制台输出如下:
reflect.ValueOf
最后,我们使用 CanSet 方法判断,指针指向的对象是否可以被修改,如果可以被修改,那么再使用 SetXX 方法修改变量的值。
reflect.ValueOf
Go语言反射修改变量
通过反射的 Set 方法修改变量的值
package main import ( "fmt" "reflect" ) func main() { fmt.Println("嗨客网(www.haicoder.net)") var x = 1024 var str = "HaiCoder" xValue := reflect.ValueOf(&x).Elem() strValue := reflect.ValueOf(&str).Elem() newXValue := reflect.ValueOf(20140) newStrValue := reflect.ValueOf("haicoder") if xValue.CanSet(){ xValue.Set(newXValue) fmt.Println("New xValue =", xValue) } if strValue.CanSet(){ strValue.Set(newStrValue) fmt.Println("New strValue =", strValue) } }
程序运行后,控制台输出如下:
reflect.ValueOf
Go语言反射修改变量总结
通过反射修改变量的值,有两种方法,一种是使用 Set 方法,一种是使用 SetXXX() 方法,比如 SetString()、SetInt() 等。Go 语言反射修改变量语法:
reflect.ValueOf(&x).Elem().Set()
Go 语言反射修改变量语法:
reflect.ValueOf(&x).Elem().SetXXX()