开发者

How to force compiler to control value/pointer-to-value func arguments?

开发者 https://www.devze.com 2023-01-18 00:44 出处:网络
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.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消