Methods are functions with a receiver—func (p Person) Greet() string. Receivers can be value or pointer; pointer receivers can mutate and avoid copying large structs.
Value vs pointer receivers
func (p Person) String() string { ... } // value receiver
func (p *Person) Birthday() { p.Age++ } // pointer receiver
Be consistent: if any method needs a pointer receiver, usually use pointer receivers for all methods on that type.
Method sets and interfaces
A type satisfies an interface if it has the required methods. Pointer and value receivers affect which interfaces a value satisfies—*T often needed when methods use pointer receivers.
Important interview questions and answers
- Q: When use pointer receiver?
A: When mutating the receiver or avoiding copy of large structs; also when methods must match pointer-based interface satisfaction. - Q: Methods on non-struct types?
A: Any named type (except pointer to built-in) can have methods—e.g.type MyInt int.
Self-check
- Which receiver type can modify struct fields?
- Can you define methods on int directly?
Pitfall: Mixing value and pointer receivers inconsistently can break interface satisfaction—pick one style per type when possible.
Interview prep
- Pointer receiver when?
When mutating the receiver or avoiding copy of large structs; be consistent across methods.
- Methods on int?
Not on bare int—define a named type like
type MyInt intfirst.