Choose pointer versus value receivers
Choose pointer versus value receivers
A value receiver receives a copy of the value. A pointer receiver receives a copy of a pointer and can change the original value through it. Choose a pointer receiver when a method needs to update the receiver itself. A value receiver is often appropriate for a small value whose operations return new results.
package main
import ( "fmt")
type Counter struct{ N int }
func (c Counter) TryAdd() { c.N++ }func (c *Counter) Add() { c.N++ }func main() { c := Counter{N: 2} c.TryAdd() fmt.Println(c.N) (&c).Add() fmt.Println(c.N)}TryAdd modifies only its local copy. Add dereferences the pointer when updating N. The caller still owns the original counter. Automatic addressing is introduced in the next lesson; here the pointer is explicit.
Expected output:
23A value receiver is not a deep copy
package main
import ( "fmt")
type List struct{ Items []int }
func (l List) SetFirst(n int) { l.Items[0] = n }func main() { l := List{Items: []int{1, 2}} l.SetFirst(9) fmt.Println(l.Items)}The copied slice descriptor shares the backing array, so changing an element is visible to the caller. Copying a struct does not recursively copy referenced data. This example requires a nonempty slice; real APIs should validate or document that condition.
Expected output:
[9 2]Try it locally
Define Wallet with Balance int. Implement a pointer receiver Deposit(n int) for positive n, ignoring other amounts. Deposit 7 into a balance of 10 and print the result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Methods 02: Choose pointer versus value receivers
Check the lesson objective before moving on.
Which receiver directly updates a field of the original struct?
Can a value receiver mutate a shared slice element?