How to force compiler to control value/pointer-to-value func arguments?
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?
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.
No. At compile time, interface{}
, the empty interface, is any type.
all types implement the empty interface:
interface{}
Interface types
精彩评论