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) |
More Related questions...