Structs and Interfaces
The API Design That Finally Clicked
Notifier (base class)
βββ EmailNotifier
βββ SMSNotifier
βββ SlackNotifiertype Notifier interface {
Send(message string) error
}
type EmailNotifier struct { /* ... */ }
func (e *EmailNotifier) Send(message string) error { /* ... */ }
type SMSNotifier struct { /* ... */ }
func (s *SMSNotifier) Send(message string) error { /* ... */ }
type SlackNotifier struct { /* ... */ }
func (s *SlackNotifier) Send(message string) error { /* ... */ }
// This just works!
func notify(n Notifier, msg string) {
n.Send(msg)
}Structs: Organizing Data
Basic Struct
Creating Struct Instances
Accessing Fields
Pointers to Structs
Anonymous Structs
Struct Embedding (Composition)
Anonymous Embedding (Promoted Fields)
Methods on Structs
When to Use Pointer Receivers
Interfaces: Defining Behavior
Interface Declaration
Implementing Interfaces
Interface Satisfaction Example
Empty Interface
Type Assertions
Type Switches
Standard Library Interfaces
io.Reader and io.Writer
Stringer Interface
Interface Embedding
Practical Example: Plugin System
Struct Tags
Your Challenge
Key Takeaways
What I Learned
Last updated