1 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超7個(gè)贊
簡單的解決方案
想通了——不需要使用反射。在接口中存儲(chǔ)值的地址將允許您通過對接口指針使用類型斷言和取消引用來完成此操作:
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
使用多個(gè)函數(shù)
如果您想抽象掉類型斷言和取消引用:
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 關(guān)注
- 99 瀏覽
添加回答
舉報(bào)