2 回答
TA贡献1820条经验 获得超10个赞
用作interface{}参数类型。类型断言指针类型。取消引用指针以设置值。
func UpdateRef(variadic ...interface{}) {
for _, v := range variadic {
if v, ok := v.(*string); ok {
*v = "New ref val"
}
}
}
将指针传递给函数:
ref := "Hey"
i := 500
UpdateRef(&ref, &i)
fmt.Println(ref) // prints “New ref val”
TA贡献1828条经验 获得超6个赞
你刚才
package main
import (
"reflect"
)
// back-end
func UpdateRef(variadic ...interface{}) {
for _, v := range variadic {
kind := reflect.TypeOf(v).Kind()
if kind == reflect.Pointer {
reflect.ValueOf(v).Elem().Set(reflect.ValueOf("New ref val"))
}
}
}
// front-end
func main() {
ref := "Hey" // starts as "Hey"
// To modify a reflection object, the value must be settable.
UpdateRef(&ref, 500) // ends at "New ref val"
println(ref)
}
查看 golang 博客:https ://go.dev/blog/laws-of-reflection 。
编码快乐!
- 2 回答
- 0 关注
- 84 浏览
添加回答
举报