tags:

views:

52

answers:

2

Hi! Dealing with go's funcs I discovered that 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  A: 

No. At compile time, interface{}, the empty interface, is any type.

all types implement the empty interface: interface{} Interface types

peterSO
Yep, under the current design of Go, it looks like that. Petty.
PGene
+1  A: 

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.

MizardX
Yes, that's exactly what I've done to work around the problem. However, reflection way seems to be labored and a bit crutchy. Moreover, it's useless in compile-time.
PGene