Go - Methods & Receivers
Beginner 10/10
Teacher 10/10
Architect 10/10
Try it: Write
func (c *Counter) Inc()
and show that it modifies the original variable.Value vs Pointer Receiver
type Counter int
func (c Counter) Value() int { return int(c) }
func (c *Counter) Inc(){ *c++ }
Guidelines
- Use pointer receivers to mutate or avoid copying.
- Be consistent across a type’s methods.
Common errors
- Mixing value and pointer receivers on the same type inconsistently.
Practice
- Add
Dec()
andReset()
methods toCounter
; decide pointer vs value receiver.
Quick quiz
- When should you prefer pointer receivers?