Receivers and Methods as Pointers and Values
Explore the differences between pointer and value receivers in Go methods. Learn when to define methods on pointers to modify struct data and when value receivers suffice. Understand how Go handles method calls on pointers and values seamlessly, and see how methods can be passed as values or parameters for flexible programming.
We'll cover the following...
Pointer or value as a receiver
The recv is most often a pointer to the receiver-type for performance reasons (because we don’t make a copy of the value, as would be the case with call by value); this is especially true when the receiver type is a struct. Define the method on a pointer type if you need the method to modify the data the receiver points to. Otherwise, it is often cleaner to define the method on a normal value type.
This is illustrated in the following example :
In the above code, at line 6, we make a struct of type B with one integer field thing. Look at the header of change() method at line 10: func (b *B) change(). The part (b *B) shows that only the pointer to B type object can call this method. This method is changing its internal field thing by assigning the value of 1 to it. Now, look at the header of the write() method at line 12: func (b B) write() string. The part (b B) shows that only the B type object can call this method. This method is returning its internal field thing ...