Pointers go-写入接口{}的函数
我想将指向某个对象的指针传递到函数中,在编译时不知道它的类型,让函数写入它。以下是我认为有效的方法:Pointers go-写入接口{}的函数,pointers,go,Pointers,Go,我想将指向某个对象的指针传递到函数中,在编译时不知道它的类型,让函数写入它。以下是我认为有效的方法: func foo(dest interface{}) { switch (dest).(type) { case *int: fmt.Println("got int") *dest = 1 // handle other cases... } } 但是,使用*int输入调用 func main() { bar := 2
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的间接属性无效(类型接口{})
我做错了什么?dest仍然是
接口{}
类型。你也必须在作业期间施展:
*dest.(*int) = 1
dest仍然是
接口{}
类型。你也必须在作业期间施展:
*dest.(*int) = 1
在这段代码中(顺便说一句,您不需要使用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...
}
}
…但是一个真正“记住”类型的开关会更好(从)
在这段代码中(顺便说一句,您不需要使用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...
}
}
…但是一个真正“记住”类型的开关会更好(从)
这个问题似乎有点老了,但我已经找到了一种更通用的方法来处理这个问题,使用反射,它不如其他解决方案快,但它适用于传递给函数的任何其他类型
func foo(dest interface{}) {
destVal := reflect.ValueOf(dest)
val := reflect.ValueOf(1)
if destVal.Kind() == reflect.Ptr && destVal.Elem().Kind() == val.Kind() {
if destElem := destVal.Elem(); destElem.CanSet() {
destElem.Set(val)
}
}
}
这个问题似乎有点老了,但我已经找到了一种更通用的方法来使用反射来处理这个问题,它没有其他解决方案那么快,但它适用于传递给函数的任何其他类型
func foo(dest interface{}) {
destVal := reflect.ValueOf(dest)
val := reflect.ValueOf(1)
if destVal.Kind() == reflect.Ptr && destVal.Elem().Kind() == val.Kind() {
if destElem := destVal.Elem(); destElem.CanSet() {
destElem.Set(val)
}
}
}
回答得很好。谢谢:)如果dest有一个未知的type@samix73我不理解你的问题,这个函数已经使用了一个
接口{}
,这个接口几乎是未知的Go@evertheylen我是说如果我用这个函数处理太多的类型,我们不能为传递给此服务器的每个类型定义一个开关案例function@samix73我真的不明白你的意思。在像Go这样的类型化语言中,如果你不知道它的类型,你就不能用dest
做很多事情。回答得很好。谢谢:)如果dest有一个未知的type@samix73我不理解你的问题,这个函数已经使用了一个接口{}
,这个接口几乎是未知的Go@evertheylen我是说如果我用这个函数处理太多的类型,我们不能为传递给此服务器的每个类型定义一个开关案例function@samix73我真的不明白你的意思。在像Go这样的类型化语言中,如果你不知道它是类型,你就不能用dest
做很多事情。我现在明白你的意思了。然而,这闻起来很像你只想要泛型:)我现在明白你的意思了。然而,这闻起来很像你只想要泛型:)