Design receiver consistency
Design receiver consistency
Choose receiver types according to the meaning of your API. Pointer receivers often fit mutable state; value receivers often fit small values with operations returning new values. Consistency is a design guideline, not a language requirement. Avoid copying synchronization primitives that must not be copied after use.
package main
import ( "fmt")
type Counter struct{ n int }
func (c *Counter) Add(n int) { c.n += n }func (c *Counter) Value() int { return c.n }func main() { var c Counter c.Add(4) c.Add(3) fmt.Println(c.Value())}Both methods use pointer receivers, even the read-only Value method. The zero value works without a constructor. Pointer receivers do not provide thread safety; concurrent mutation still needs synchronization, covered later.
Expected output:
7Return a new value instead of mutating
package main
import ( "fmt")
type Point struct{ X, Y int }
func (p Point) Move(dx, dy int) Point { p.X += dx; p.Y += dy; return p }func (p Point) Sum() int { return p.X + p.Y }func main() { p := Point{X: 1, Y: 2} q := p.Move(3, 4) fmt.Println(p.Sum(), q.Sum())}Move returns a new Point; the original is unchanged because it contains only int fields. Document this contract. Do not select receivers solely on a performance guess: allocation and copying costs depend on the compiler and workload.
Expected output:
3 10Try it locally
Define Score int with value methods Increase(n int) Score and Value() int. Starting from 10, create a score increased by 5 and print both without mutating the original.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Methods 07: Design receiver consistency
Check the lesson objective before moving on.
Are pointer receivers automatically safe for concurrent calls?
Which design suits a small value whose operations return independent new values?