Pointer receiver (*T) — method operates on original, can modify, avoids copy. Value receiver (T) — method operates on copy, changes discarded.
Pointer receivers are necessary for mutation. They also avoid copying large structs.
1type Stack struct {2 items []interface{}3}45func (s *Stack) Push(item interface{}) {6 s.items = append(s.items, item)7}89func (s *Stack) Pop() (interface{}, bool) {10 if len(s.items) == 0 {11 return nil, false12 }13 item := s.items[len(s.items)-1]14 s.items = s.items[:len(s.items)-1]15 return item, true16}
When to use:
Common mistakes: