3 回答
TA贡献1963条经验 获得超6个赞
在这段代码中(顺便说一句,您不需要周围的括号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...
}
}
TA贡献1790条经验 获得超9个赞
这个问题似乎有点老了,但我提出了一种使用反射来处理这个问题的更通用的方法,它不如其他解决方案快,但它适用于您传递给函数的任何其他类型
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)
}
}
}
- 3 回答
- 0 关注
- 158 浏览
添加回答
举报