Golang / GoLang Interfaces and Object Oriented Interview Questions
How does Go's implicit interface satisfaction enable duck typing and loose coupling?
Go's implicit interface satisfaction means: if a type has the required methods, it satisfies the interface — regardless of whether the type's author ever heard of that interface. This is sometimes called structural typing or duck typing with compile-time verification.
// Third-party library defines:
type Logger interface {
Log(msg string)
}
// Your legacy type (written before the Logger interface existed):
type AppLogger struct{ prefix string }
func (a AppLogger) Log(msg string) { fmt.Println(a.prefix+":", msg) }
// AppLogger satisfies Logger with ZERO changes to either package
func useLogger(l Logger) { l.Log("hello") }
useLogger(AppLogger{prefix: "APP"}) // compiles fine
// Compile-time interface check — verify without running the code
// Idiom: blank identifier assignment causes a compile error if the interface isn't satisfied
var _ Logger = AppLogger{} // value receiver version
var _ Logger = (*AppLogger)(nil) // pointer receiver version
// Interface segregation — small interfaces are more reusable
type Reader interface { Read(p []byte) (int, error) }
type Writer interface { Write(p []byte) (int, error) }
type ReadWriter interface {
Reader // interface embedding
Writer
}
// Any type satisfying ReadWriter also satisfies Reader and Writer individually
var rw ReadWriter = os.Stdout // *os.File has both Read and Write
var r Reader = rw // ReadWriter subsumes Reader
var w Writer = rw // ReadWriter subsumes WriterThe compile-time check idiom (var _ Logger = AppLogger{}) is a Go best practice: it causes a compile error if AppLogger ever stops satisfying Logger, catching the mismatch at compile time rather than at runtime when a type assertion or assignment fails.
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...
