Why Go Disallows Method Sets on *T to Be Used by T
In Go, methods defined on a value type T can be used by both T and *T, while methods defined on a pointer type *T cannot be used by T. This seemingly arbitrary distinction stems from the complexities of memory in computer systems.
Inability to Obtain Pointers on Demand
Consider the case where a method on *T is to be called using a T variable. To achieve this, a pointer to the T variable must be obtained. However, obtaining a pointer is not always guaranteed to be possible.
Go's specification explicitly states the conditions under which an address-of operation (&) can be performed. These include accessing variables, pointer indirections, and array indexing operations. However, it excludes accessing a variable stored in a map, as in the following example:
<code class="go">res := TMap["key"].pointerMethod()</code>
In such cases, obtaining a pointer to the variable is impractical, as this would impose constraints on the runtime's implementation of data structures like maps.
Consequences of Design
This design decision has both advantages and disadvantages:
Advantages:
Disadvantages:
The above is the detailed content of Why Can\'t Go Methods Defined on *T Be Used by T?. For more information, please follow other related articles on the PHP Chinese website!