Golang / GoLang Interfaces and Object Oriented Interview Questions
How can a single Go type implement multiple interfaces simultaneously?
A type can implement any number of interfaces simultaneously — all it needs is the right set of methods. There is no limit and no explicit declaration. This enables a type to play many roles in different contexts.
// Several independent interfaces
type Saver interface { Save() error }
type Loader interface { Load() error }
type Deleter interface { Delete() error }
type Stringer interface { String() string }
// One type, many roles
type UserRepo struct{ db *sql.DB }
func (r *UserRepo) Save() error { /* INSERT */ return nil }
func (r *UserRepo) Load() error { /* SELECT */ return nil }
func (r *UserRepo) Delete() error { /* DELETE */ return nil }
func (r *UserRepo) String() string { return "UserRepo" }
// Use through different interface lenses
repo := &UserRepo{db: db}
var s Saver = repo // *UserRepo satisfies Saver
var l Loader = repo // *UserRepo satisfies Loader
var d Deleter = repo // *UserRepo satisfies Deleter
var st fmt.Stringer = repo // satisfies fmt.Stringer too
// Composed interface — all at once
type CRUD interface {
Saver
Loader
Deleter
}
var crud CRUD = repo // *UserRepo satisfies CRUD
// Passing to functions that only need part of the capability
func backup(s Saver) { s.Save() } // only needs Save
func restore(l Loader) { l.Load() } // only needs Load
backup(repo)
restore(repo)
// Verify all at compile time
var _ Saver = (*UserRepo)(nil)
var _ Loader = (*UserRepo)(nil)
var _ Deleter = (*UserRepo)(nil)
var _ CRUD = (*UserRepo)(nil)Passing repo to backup(s Saver) exposes only the Save method — the function cannot call Load or Delete even though the concrete type has them. This is the principle of minimal interface exposure: functions accept only the capability they need, reducing coupling and making code easier to understand and test.
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...
