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