Can Go\'s Method Set on Pointer Types Be Called with Regular Types?

Barbara Streisand
Release: 2024-11-17 20:37:01
Original
568 people have browsed it

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!

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