1

Given an interface, how do I obtain a pointer to the underlying value?

My naive attempt was to use a type assertion like this:

var mytypeptr *MyType = myinterface.(*MyType)

But I get:

interface conversion: MyInterface is MyType, not *MyType
ealfonso
  • 6,622
  • 5
  • 39
  • 67
  • I think you want to put `*MyType` in the `interface` int the first place here. Interface values internally contain pointers already for any type longer than a machine word; the compiler is smart enough to not make that a pointer-to-pointer when you store a `*MyType` ([here's gnarly test code to demonstrate](http://play.golang.org/p/3Y3QKTmSW8)); and `.` behaves the same for the pointer type as for the actual struct. – twotwotwo Sep 19 '14 at 19:44

1 Answers1

0

You could start with, using reflect.Indirect():

val := reflect.ValueOf(myinterface)
if val.Kind() == reflect.Ptr {
    val = reflect.Indirect(val)
}
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Is there a way to modify struct fields behind an interface without resorting to using reflect? – ealfonso Sep 19 '14 at 17:08
  • @erjoalgo considering how an interface is structured (see http://stackoverflow.com/a/23148998/6309), no: at runtime, the interface masks the underlying value. Interfaces are statically typed (http://stackoverflow.com/a/23724093/6309) – VonC Sep 19 '14 at 17:09