英文:
How to force compiler to control value/pointer-to-value func arguments?
问题
处理go的函数时,我发现当使用'generic' interface{}类型时,无法强制编译器控制我是传递值还是指向值的指针参数。
func f(o interface{}) {
...
}
最明显的解决方案是使用以下修改:
func f(o *interface{}) {
...
}
尽管这样可以成功编译,但我认为这一步不正确。那么,有没有办法表明我想传递任何指针?
英文:
Dealing with go's funcs I discovered that one can't force the compiler to control whether I pass a value or pointer-to-value argument when using 'generic' interface{} type.
func f(o interface{}) {
...
}
The most obvious solution is to use the following modification:
func f(o *interface{}) {
...
}
Although this is successfully compiled I didn't find this step right. So, is there any means to state that I want to pass any pointer?
答案1
得分: 2
你需要使用反射。
import "reflect"
func f(o interface{}) {
if _, ok := reflect.TypeOf(o).(*reflect.PtrType); !ok {
panic("不是指针")
}
// ...
}
你也可以考虑使用unsafe.Pointer
,但类型信息会丢失。
英文:
You'd have to use reflection.
import "reflect"
func f(o interface{}) {
if _, ok := reflect.Typeof(o).(*reflect.PtrType); !ok {
panic("Not a pointer")
}
// ...
}
You could also consider unsafe.Pointer
, but the type information would be lost.
答案2
得分: 1
在编译时,interface{}
,即空接口,可以表示任何类型。
> 所有类型都实现了空接口:interface{}
接口类型
英文:
No. At compile time, interface{}
, the empty interface, is any type.
> all types implement the empty
> interface: interface{}
Interface
> types
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论