1 回答
TA贡献1796条经验 获得超7个赞
简单的解决方案
想通了——不需要使用反射。在接口中存储值的地址将允许您通过对接口指针使用类型断言和取消引用来完成此操作:
package main
import "fmt"
func main() {
var object any
object = "Hi"
var a, b any
a = &object
b = &object
*a.(*any) = "Howdy"
fmt.Println(*a.(*any))
fmt.Println(*b.(*any))
}
打印日志
Howdy
Howdy
游乐场: https://go.dev/play/p/LEx8MR4ZK06
使用多个函数
如果您想抽象掉类型断言和取消引用:
package main
import "fmt"
func getStuff(a any) any {
return *a.(*any)
}
func setStuff(a, to any) {
*a.(*any) = to
}
func main() {
var object any
object = "Hi"
var a, b any
a = &object
b = &object
setStuff(a, "Howdy")
fmt.Println(getStuff(a))
fmt.Println(getStuff(b))
}
打印日志
Howdy
Howdy
游乐场: https://go.dev/play/p/RUX4cu2Cx2o
- 1 回答
- 0 关注
- 72 浏览
添加回答
举报