我想将指向某物的指针传递给函数,而在编译时不知道其类型,则将函数写入其中。这是我认为可行的方法:
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
}
产生编译器错误
invalid indirect of dest (type 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/