Golang / GoLang Interfaces and Object Oriented Interview Questions
How does interface embedding (composition) work in Go?
Go interfaces can embed other interfaces. The composed interface's method set is the union of all embedded interface method sets. This is Go's primary mechanism for building larger interface contracts from smaller, focused ones — following the Interface Segregation Principle.
// Small, focused interfaces (the Go standard library style)
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
type Closer interface {
Close() error
}
// Composed interfaces
type ReadWriter interface {
Reader // embeds Reader
Writer // embeds Writer
}
type ReadWriteCloser interface {
Reader
Writer
Closer
}
// *os.File satisfies all of the above
var f *os.File = os.Stdout
var rw ReadWriter = f // *os.File has Read + Write
var rwc ReadWriteCloser = f // *os.File has Read + Write + Close
var r Reader = rw // ReadWriter is assignable to Reader
// Your composed interface
type DataStore interface {
Reader
Writer
Flush() error
Stats() map[string]int64
}
// Any type with Read, Write, Flush, Stats satisfies DataStore
// without knowing anything about DataStoreDesign principle: prefer many small interfaces over one large interface. Small interfaces (io.Reader has 1 method, io.Writer has 1 method) are easy to satisfy and easy to mock in tests. Accept interfaces in your functions; return concrete types from constructors. The idiomatic Go proverb: "The bigger the interface, the weaker the abstraction."
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
