In Go, methods are attached to types through the use of receivers. This raises the question: what exactly is a receiver, and how does it differ from a parameter?
The Receiver: A Special Kind of Parameter
The receiver is a special case of a parameter. In the method signature func (p *Page) save() error, the receiver is p. Syntactically, the receiver is the first parameter declared in the method signature.
The primary difference between a receiver and a parameter lies in its association with the type it "belongs" to. The receiver allows the method to be associated with the type it operates on, making it more intuitive and easy to understand.
Example: save() Method
In the given method signature func (p *Page) save() error, the receiver p is a pointer to a Page type. This means that the save() method can only be called on instances of *Page. The method can access and modify the underlying Page object.
Syntax Equivalence
While the receiver is syntactically different from a parameter, it is functionally equivalent. The following two code snippets are equivalent:
func (p *Page) save() error {
The above is the detailed content of Go Methods: What\'s the Difference Between a Receiver and a Parameter?. For more information, please follow other related articles on the PHP Chinese website!