Pointer Receivers
A method receiver can be either a value or a pointer. A pointer receiver allows the method to modify the value to which the receiver points.
Syntax
type car struct {
color string
}
// Pointer receiver
func (c *car) setColor(color string) {
c.color = color
}
// Value receiver (modifies a copy, original stays same)
func (c car) setColorValue(color string) {
c.color = color
}
Automatic Conversion
Go automatically converts values to pointers (and vice-versa) when calling methods. You can call a pointer-receiver method on a value variable, and Go will handle getting the address for you.
myCar := car{color: "white"}
myCar.setColor("blue") // Works! Original is now blue.
Consistency Rule
As a general rule, if any method of a struct requires a pointer receiver, all methods of that struct should probably have pointer receivers for consistency.