Methods
Declaring methods with value and pointer receivers, and seeing how each receiver affects mutation.
A method is a function with a receiver, the value that the function is attached to. Go methods are commonly used to define behavior for a type.
A value receiver gets a copy. A pointer receiver can change the original 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 pointer receivers when a method mutates state or copying the value is undesirable. Keep receiver choices consistent where practical. A type's method set determines interface satisfaction, covered in Interfaces.
Enjoyed this? Get more software craft delivered to your inbox.