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.
More Related questions...