Home >Backend Development >Golang >Why Are Non-Addressable Values in Golang Interfaces Not Accessable by Address?
The concept of non-addressable values in Go interfaces, widely discussed in the Golang documentation and community forums, prompts the question: why can't these values be accessed through their address?
As the Go wiki on MethodSets (https://github.com/golang/go/wiki/MethodSets#interfaces) points out, "The concrete value stored in an interface is not addressable, in the same way, that a map element is not addressable." The non-addressability of map elements is well-understood and explained in detail in the companion post "Why are map values not addressable?".
However, the underlying reason for non-addressability of values in interfaces is not as clear. Why does the language design impose this restriction?
The answer lies in preserving type integrity. A pointer to a value of a specific type, when assigned to an interface, should point to a value of that type. However, if the interface could contain values of different types, the pointer would become invalid whenever a value of a different type was assigned to the interface.
To illustrate, consider an interface I and two types A and B that implement I:
type I interface{} type A int type B string
If we store an A value in I and take the address of that value, the resulting pointer would be to type *A. However, if we subsequently assign a B value to I, the pointer would become invalid.
The non-addressability of interface values has direct implications for methods with pointer receivers. Such methods expect a pointer to a specific concrete type. Since a non-pointer value in an interface is not addressable, it cannot be passed to a method with a pointer receiver, leading to the error:
<type> does not implement <interface> (<name> method has pointer receiver)
In summary, the reason for non-addressability of values in Go interfaces is to protect type integrity. A pointer to a value of a specific type should always point to a value of that type, which cannot be guaranteed if the value is stored in an interface that can hold values of different types.
The above is the detailed content of Why Are Non-Addressable Values in Golang Interfaces Not Accessable by Address?. For more information, please follow other related articles on the PHP Chinese website!