Home > Backend Development > Golang > Why Are Non-Pointer Values in Go Interfaces Not Addressable?

Why Are Non-Pointer Values in Go Interfaces Not Addressable?

Barbara Streisand
Release: 2024-12-06 01:33:10
Original
388 people have browsed it

Why Are Non-Pointer Values in Go Interfaces Not Addressable?

Why Interfaces with Non-Pointer Values are Not Addressable in Go

Golang's interface documentation suggests that stored values within interfaces are not addressable, akin to elements in a map. This raises the question of why interface values are non-addressable.

tl;dr: Maintaining Type Integrity

To preserve type integrity, non-pointer values stored in interfaces are not addressable. Consider a pointer (*A) pointing to a value of type A within an interface. If a different type (e.g., B) were subsequently stored in the interface, the pointer to A would become invalid, compromising type safety.

Addressing Implications

If interface values were addressable, it would lead to unexpected effects. For instance, with an interface I, two types A and B implementing I, and a stored A in an I instance, taking the address of the stored value would allow modifications to the original value through that address. However, when another value B is stored in I, the pointer to the original A value would become invalid.

Pointer Caveat

While non-pointer interface values are not addressable, it is possible to obtain a pointer to a copy of the value using explicit casting, e.g., var a2 A = i.(A) followed by var aPtr *A = &a2.

Conclusion

Non-addressability of interface values ensures type integrity by preventing invalid pointer references when values of different types are stored in the interface.

The above is the detailed content of Why Are Non-Pointer Values in Go Interfaces Not Addressable?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template