Interface types and method sets
Interface satisfaction depends on method sets, not intent; pointer and value receiver choices directly affect assignability.
Canonical guidance
- a type implements an interface implicitly when its method set matches
Tand*Tdo not have the same method set- interface values carry a dynamic type and value pair
Use when
- diagnosing assignability failures
- reviewing pointer versus value receivers
- explaining why an interface call compiles or not
Avoid
- assuming “has the method somewhere” is enough
- forgetting that only
*Thas methods with pointer receivers - treating interface satisfaction as nominal inheritance
Preferred pattern
type Reader interface {
Read([]byte) (int, error)
}
Anti-pattern
- assigning a
Tvalue to an interface that requires a method defined only on*T
Explanation: This is tempting because method-call syntax may auto-address some values, but interface satisfaction uses method sets, not call-site convenience.
Why
- method-set confusion is one of the highest-value retrieval gaps for code review and compile-error diagnosis
Related pages
Sources
- The Go Programming Language Specification - Go Team
- Go Data Structures: Interfaces - Russ Cox