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()) // 10
Practical 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.
More Related questions...