Design small consumer interfaces
Design small consumer interfaces
Define an interface around what the calling code actually needs. A small consumer-defined interface allows multiple implementations without requiring unrelated methods. Prefer a concrete parameter when there is no useful abstraction; interfaces are not required for every type.
package main
import ( "fmt")
type Pricer interface{ Price() int }type Product struct{ Cents int }
func (p Product) Price() int { return p.Cents }func (p Product) Label() string { return "product" }func total(p Pricer, n int) int { return p.Price() * n }func main() { fmt.Println(total(Product{Cents: 250}, 3))}The consumer total needs only Price. Product also has Label, but total cannot call it through Pricer. These fixed small amounts avoid overflow; real money calculations need range and currency checks.
Expected output:
750Accept a second implementation
package main
import ( "fmt")
type Sizer interface{ Size() int }type Box struct{ Items int }
func (b Box) Size() int { return b.Items }
type Bag []string
func (b Bag) Size() int { return len(b) }func fits(s Sizer, limit int) bool { return s.Size() <= limit }func main() { fmt.Println(fits(Box{Items: 4}, 3)) fmt.Println(fits(Bag{"a", "b"}, 3))}Both implementations satisfy Sizer without sharing a base type. fits relies on a documented meaning of Size (item count), not just its signature. Method matching alone cannot prove semantic correctness.
Expected output:
falsetrueTry it locally
Define a consumer interface Named with Name() string. Write greet(n Named) returning "Hello, " plus the name. Use a Person named Ada.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Interfaces 02: Design small consumer interfaces
Check the lesson objective before moving on.
What should a consumer interface describe?
Does matching a method signature prove its meaning is correct?