Intermediate 18 min readModule: Module 7: Interfaces & Implicit Composition
Implicit Interfaces & Type Assertions
Implement interfaces implicitly without 'implements' keywords, and inspect dynamic types with type switches.
What You Will Learn in This Lesson
- Implicit interface satisfaction: if a struct implements the methods, it implements the interface
- The io.Reader and io.Writer universal interfaces
- Type assertions (val, ok := i.(MyType)) and type switches
Introduction & Core Concept
In Go, interfaces are satisfied implicitly. A type implements an interface by simply implementing its methods. There is no explicit 'implements' declaration.
WHY DOES THIS MATTER IN THE REAL WORLD?
Implicit interfaces allow you to define interfaces for third-party packages without modifying their source code.
Implicit Interface Implementation
gogo
1234567891011121314151617package mainimport "fmt"type Speaker interface {Speak() string}type Bot struct{}func (b Bot) Speak() string { return "Beep Boop" }func greet(s Speaker) {fmt.Println(s.Speak())}func main() {greet(Bot{}) // Bot implicitly satisfies Speaker}
Line-by-Line Technical Breakdown
1Keep interfaces small: 'The bigger the interface, the weaker the abstraction' (Rob Pike).
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[GO]
GO SOURCE EDITOR
Interactive Live CodeIndustry Best Practices & Professional Standards
- Define 1-method or 2-method interfaces at the consumer site.
Lesson Summary & Core Takeaways
- Implicit interfaces decouple Go modules cleanly.