gpt4 book ai didi

pointers - go - 写入接口(interface)的函数{}

转载 作者:IT王子 更新时间:2023-10-29 01:51:19 26 4
gpt4 key购买 nike

我想将一个指向某个东西的指针传递给一个函数,在编译时不知道它的类型,让函数写入它。这是我认为可行的方法:

func foo(dest interface{}) {
switch (dest).(type) {
case *int:
fmt.Println("got int")
*dest = 1
// handle other cases...
}
}

但是,使用 *int 输入调用它

func main() {
bar := 2
foo(&bar)
fmt.Println(bar) // expect 1
}

产生编译错误

dest 的间接指令无效(类型接口(interface) {})

我在这里做错了什么?

最佳答案

在这段代码中(顺便说一句,您不需要 dest 周围的括号),一旦您输入一个案例,您基本上就忘记了类型:

func foo(dest interface{}) {
switch dest.(type) {
case *int:
fmt.Println("got int")
*dest = 1
// handle other cases...
}
}

也就是说,根据编译器,dest 仍然是 interface{} 类型,这使得 *dest = 1 错误。

可以使用更多类似这样的类型断言...

func foo(dest interface{}) {
switch dest.(type) {
case *int:
fmt.Println("got int")
*dest.(*int) = 1
// handle other cases...
}
}

...但是实际上“记住”类型的开关会好得多(来自 Effective Go )

func foo(dest interface{}) {
switch dest := dest.(type) {
case *int:
fmt.Println("got int")
*dest = 1
// handle other cases...
}
}

关于pointers - go - 写入接口(interface)的函数{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32024660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com