Methods
Declaring methods with value and pointer receivers, and seeing how each receiver affects mutation.
A method is a function attached to a type. Its receiver is the value the method works on, like the input to an ordinary function.
A value receiver gets a copy of the value. A pointer receiver gets its address, so the method can change the caller's value:
package main
import "fmt"
type Counter struct {
Value int
}
func (c Counter) Current() int {
return c.Value
}
func (c *Counter) Increment() {
c.Value++
}
func main() {
counter := Counter{}
counter.Increment()
fmt.Println(counter.Current()) // 1
}In production
Use a pointer receiver when the method changes the caller's value or the value is large to copy. Keep receiver choices consistent. The methods a type provides affect whether it can be used as an interface.
Enjoyed this? Get more software craft delivered to your inbox.