In the following code
var a int
var b interface{}
b = a
fmt.Printf("%T, %T \n", a, &a)
fmt.Printf("%T, %T \n", b, &b)
output:
int, *int
int, *interface {}
I would expect the type of &b to be a pointer on int.
I have two questions:
1) Why is it a pointer on interface{} ?
2) How could I get a pointer on the original type ?
&b=> this is the address operator applied on the variableb, whose type isinterface{}. So&bwill be a pointer of type*interface{}, pointing to the variableb. If you take the address of a variable of typeT, the result will always be of type*T.You cannot obtain the address of the variable
afromb, because the assignment:Simply copies the value of
aintob. It wraps the value ofain an interface value of typeinterface{}, and stores this interface value intob. This value is completely detached froma.In general, all assignments copy the values being assigned. There are no reference types in Go. The closest you can get to what you want is if you store the address of
ainbin the first place, e.g.:Then you can use type assertion to get out
a's address fromblike this:This outputs (try it on the Go Playground):
(Note: when you simply print
b, since it is of an interface type, thefmtpackage prints the (concrete) value wrapped in it.)See related questions:
How to get a pointer to a variable that's masked as an interface?
Changing pointer type and value under interface with reflection