Golang / GoLang Interfaces and Object Oriented Interview Questions
Why can't you always use a value of type T where *T is needed for interface satisfaction?
Go's method set rules determine which methods can be called on a value of a given type. The asymmetry is:
| Type in expression | Method set |
|---|---|
| T (value type) | Only methods declared with value receiver (func (t T)) |
| *T (pointer type) | Methods declared with value receiver + methods with pointer receiver (func (t *T)) |
type Counter struct{ n int }
func (c Counter) Get() int { return c.n } // value receiver
func (c *Counter) Add(d int) { c.n += d } // pointer receiver
// Interface requiring pointer receiver method
type Adder interface { Add(int) }
var a1 Adder = &Counter{} // OK — *Counter has Add()
// var a2 Adder = Counter{} // COMPILE ERROR: Counter does not implement Adder
// (Add has pointer receiver)
// Why the asymmetry?
// When you assign Counter{} to an interface, Go cannot take its address —
// the interface stores a copy, and pointer receiver methods need the ORIGINAL.
// A *Counter stores the address, so pointer receiver methods can mutate it.
// Addressable variables work fine without interfaces:
c := Counter{} // addressable
c.Add(5) // Go auto-takes &c → compiles fine
fmt.Println(c.Get()) // 5
// Non-addressable — method call fails
// Counter{}.Add(5) // COMPILE ERROR: cannot take the address of Counter{}
// Correct pattern: use *Counter when ANY method uses pointer receiver
var a Adder = &Counter{}
a.Add(10)
// Access Get() via type assertion:
fmt.Println(a.(*Counter).Get()) // 10Practical rule: if a type has any method with a pointer receiver, use *T everywhere (fields, slices, interface assignments). Mixing value and pointer receivers is a common source of interface satisfaction failures.
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...
