Home > Article > Backend Development > Why are Go methods on T accessible to *T, but not vice versa?
In Go, methods on T (value receiver) affect a copy of the value, while those on T (pointer receiver) alter the actual value. This distinction has puzzled many, leading to questions about why methods on T are also accessible to T, but not vice versa.
The ability to call methods on T using T stems from a simple principle: pointers hold the memory address of a value, and dereferencing them retrieves the value itself. Therefore, passing myT to a method that takes T is equivalent to copying a blob of memory, guaranteeing access to the underlying value.
Conversely, obtaining a *T from a T is not always straightforward. In some cases, such as values stored within maps, function returns, or interfaces, retrieving a static memory address might prove challenging.
According to the Go specification, addressable operands include variables, pointer indirections, and specific struct or array operations. However, composite literals are an exception.
This distinction has pros and cons:
Pros:
Cons:
Go's design choice to separate method sets on T and *T is based on practical considerations and helps preserve memory safety and performance. While it introduces some limitations, it also provides benefits such as clarity and reduced aliasing. By understanding these reasons, developers can effectively use Go's method receiver semantics to achieve desired functionality while adhering to its principles.
The above is the detailed content of Why are Go methods on T accessible to *T, but not vice versa?. For more information, please follow other related articles on the PHP Chinese website!