Home > Article > Backend Development > Can Go\'s Method Set on Pointer Types Be Called with Regular Types?
Go Method Sets: Can You Call Methods of Pointer Types on Regular Types?
The Go specification defines the method set of a type as all methods with a receiver type matching that type. However, it also states that the method set of a pointer type (*T) includes both its own methods and the methods of its corresponding non-pointer type (T). This raises the question: can you call methods of pointer types on regular types?
Despite the specification's wording, the answer is no. You cannot directly invoke a method designed to be called on a pointer type (*T) using a regular type (T). This is because method calls must match the receiver type exactly.
However, the compiler provides a clever workaround. It automatically dereferences regular type receivers and invokes the pointer type method instead. This is equivalent to manually dereferencing the receiver and calling the pointer type method explicitly: user.SayWat() becomes (&user).SayWat().
The above is the detailed content of Can Go\'s Method Set on Pointer Types Be Called with Regular Types?. For more information, please follow other related articles on the PHP Chinese website!