Pointer receiver (*T) — receives a pointer to the value, can modify the original, avoids copying. Value receiver (T) — receives a copy, changes don't affect the original.
Pointer receivers are necessary when a method needs to mutate the receiver's state. They're also preferred for large structs to avoid the cost of copying.
1type Queue struct {2 items []string3}45// Pointer receiver — mutates the queue6func (q *Queue) Push(item string) {7 q.items = append(q.items, item)8}910func (q *Queue) Pop() (string, bool) {11 if len(q.items) == 0 {12 return "", false13 }14 item := q.items[0]15 q.items = q.items[1:]16 return item, true17}
Value receivers are appropriate for small, immutable types where copying is trivial and you want read-only semantics.
1type Color struct{ R, G, B uint8 }23func (c Color) Hex() string {4 return fmt.Sprintf("#%02x%02x%02x", c.R, c.G, c.B)5}
When to use:
Common mistakes: