1

Interfaces already contain a pointer to a value, and I in my case it's a struct, and I need to get a struct pointer out of an interface{}.

The use case is with sync.Map, where I put a struct containing a lock into the map, and with the Load() method I can read an interface{} value. I want to get the pointer to the original struct, so I don't copy the lock.

The alternative is to add a pointer to the struct to the Map instead, then read it back and cast the interface{} to the struct pointer, but I'm curious if the first case can be achieved.

icza
  • 389,944
  • 63
  • 907
  • 827
Ivan Voras
  • 1,895
  • 1
  • 13
  • 20
  • 2
    This is what [type assertions](https://golang.org/ref/spec#Type_assertions) are for. Another mean is [type switches](https://golang.org/ref/spec#Switch_statements). – icza Jul 17 '18 at 10:27

1 Answers1

3

You can't do that. If you "wrap" a non-pointer value in an interface, you can only get a non-pointer value out of it, using either a type assertion or a type switch. And since type assertion expressions are not addressable, you can't get the address of the "value" wrapped in the interface.

If you only have a value wrapped in an interface, you won't be able to get a pointer to the original value that was wrapped in the interface. Why? Because the value wrapped in the interface may only be a copy, completely detached from the original. See examples and explanation here: How can a slice contain itself?

Note that under the hood the value actually wrapped may or may not be a pointer (depending on the value's size) even if you wrapped a non-pointer value, but this is implementation detail and is hidden from you. When you extract the value, you will of course get a non-pointer.

icza
  • 389,944
  • 63
  • 907
  • 827