You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
var x int = 10
v := reflect.ValueOf(&x).Elem()
v.SetInt(20)
fmt.Println(x) // 输出:20
动态调用函数
使用reflect.ValueOf()函数获取到函数的值信息后,可以使用反射提供的Call()方法来动态调用函数,例如:
func add(a, b int) int {
return a + b
}
f := reflect.ValueOf(add)
result := f.Call([]reflect.Value{reflect.ValueOf(1), reflect.ValueOf(2)})
fmt.Println(result[0].Int()) // 输出:3
动态创建对象
使用reflect.New()函数可以动态创建一个对象,例如:
type Person struct {
Name string
Age int
}
pType := reflect.TypeOf(Person{})
pValue := reflect.New(pType)
p := pValue.Interface().(*Person)
p.Name = "Alice"
p.Age = 20
fmt.Println(p) // 输出:&{Alice 20}
求更新3.5反射小节
The text was updated successfully, but these errors were encountered: