Golang / GoLang Interfaces and Object Oriented Interview Questions
What is the difference between value receivers and pointer receivers in Go methods?
Go methods are functions associated with a type. The receiver appears before the method name: func (t T) Method() (value receiver) or func (t *T) Method() (pointer receiver). Choosing correctly is essential for correctness and performance.
type Counter struct{ count int }
// Value receiver — operates on a COPY of Counter
func (c Counter) Value() int { return c.count }
// Pointer receiver — operates on the ORIGINAL Counter
func (c *Counter) Increment() { c.count++ }
func (c *Counter) Reset() { c.count = 0 }
c := Counter{}
c.Increment() // Go auto-takes &c; c.count becomes 1
fmt.Println(c.Value()) // 1
// Method set rules — critical for interface satisfaction:
// Value T: method set = {value receiver methods}
// Pointer *T: method set = {value receiver methods} ∪ {pointer receiver methods}
type Stringer interface{ String() string }
type MyType struct{ v int }
func (m *MyType) String() string { return fmt.Sprintf("%d", m.v) } // pointer receiver
var s Stringer = &MyType{42} // OK — *MyType has String()
// var s2 Stringer = MyType{42} // COMPILE ERROR — MyType (value) does NOT have String()
// Rule of thumb for choosing receiver type:
// Use POINTER receiver when:
// 1. The method must mutate the receiver
// 2. The receiver is large (avoid expensive copies)
// 3. The struct has non-copyable fields (sync.Mutex)
// Use VALUE receiver when:
// 1. The method is purely read-only
// 2. The type is small and immutable (time.Time, net/netip.Addr)
// Consistency rule: if ANY method uses pointer receiver, use pointer for all| Type used | Method set |
|---|---|
| T (value) | Methods with value receiver (T) |
| *T (pointer) | Methods with value receiver (T) + methods with pointer receiver (*T) |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
