Golang / GoLang Interfaces and Object Oriented Interview Questions
Explain the Go design principle: 'Accept interfaces, return concrete types'.
This principle appears in Russ Cox's writings and the Go wiki. It guides the design of clean, testable, and composable APIs.
- Accept interfaces: function parameters typed as interfaces are flexible — callers can pass any concrete type satisfying the interface, including mocks in tests.
- Return concrete types: function return types should be concrete structs or pointers, not interfaces. This gives callers full access to all methods of the returned type. If you return an interface, callers cannot access methods added later unless the interface is updated.
// GOOD: Accept interface, return concrete type
type Logger interface{ Log(string) }
type UserService struct {
db DB
logger Logger // injected — any Logger impl works (including mocks)
}
// Constructor returns *UserService (concrete), not some Service interface
func NewUserService(db DB, logger Logger) *UserService {
return &UserService{db: db, logger: logger}
}
// Method accepts io.Reader (interface) — any source of bytes works
func (s *UserService) ImportUsers(r io.Reader) error {
// reads from file, HTTP body, bytes.Buffer, etc.
}
// BAD: Returning an interface locks callers in
func NewUserService2(db DB) UserServicer { // interface return
return &UserService{db: db}
// Caller cannot call methods on *UserService not in UserServicer
// Adding a method to *UserService doesn't help callers
}
// Exception: when the return type IS genuinely polymorphic (factory pattern)
func NewStorage(driver string) Storage { // Storage is an interface
switch driver {
case "s3": return NewS3Storage()
case "local": return NewLocalStorage()
}
return nil
}Exception: returning interfaces is appropriate in genuine factory patterns where the caller should not care about the concrete type — only the contract. The error return type is the canonical example: always returned as the interface error, never as a concrete *MyError.
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...
