Receivers and Methods as Pointers and Values
In this lesson, you'll study the difference between the value and the pointer type in Go to receive a result or call a method.
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 :
package mainimport ("fmt")type B struct {thing int}func (b *B) change() { b.thing = 1 }func (b B) write() string { return fmt.Sprint(b) }func main() {var b1 B // b1 is a valueb1.change()fmt.Println(b1.write())b2 := new(B) // b2 is a pointerb2.change()fmt.Println(b2.write())}
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
after converting it to type string.
Note: The ...