Go does not have classes or inheritance, so how does it achieve code reuse through embedding and composition?
Last updated
Go favors composition over inheritance: a struct embeds other structs or interfaces to reuse their fields and methods, and interfaces define behavior that any type can satisfy implicitly, giving reuse and polymorphism without class hierarchies.
Struct embedding (promotion):
An embedded type's fields and methods are promoted to the outer struct, so the outer type can call them directly.
This is composition, not inheritance: the outer type "has-a" embedded value, and you can override by defining a method with the same name.
Interface embedding: Interfaces compose by embedding smaller interfaces (e.g.
io.ReadWriterembedsReaderandWriter).Polymorphism via implicit interfaces: Any type with the right methods satisfies an interface, no
implementsdeclaration, decoupling callers from concrete types.Why no inheritance: Avoids fragile deep hierarchies; behavior is shared by delegation and small interfaces instead.
[lang:go]
type Logger struct{}
func (Logger) Log(msg string) { fmt.Println(msg) }
type Server struct {
Logger // embedded
addr string
}
s := Server{addr: ":80"}
s.Log("started") // promoted method
- https://pkg.go.dev/github.com/rajkumar-km/go-play/go-basics/15-composition
- https://github.com/cheatsnake/backend-cheats
- https://go.dev/talks/2012/splash.article
- https://go.dev/talks/2012/chat.slide
- https://pkg.go.dev/github.com/edgardnogueira/go-patterns/idioms/interfaces
- https://go.dev/talks/2015/go4cpp.slide
- https://go.dev/talks/2014/go4java.slide