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() and Reset() methods to Counter; decide pointer vs value receiver.

Quick quiz

  1. When should you prefer pointer receivers?
Show answer When mutating the receiver or when copying the value would be expensive.