interfaces Flashcards
(10 cards)
Interface Basics
type Speaker interface { Speak() string }
Key Points:
* Named collection of method signatures
* Types implicitly satisfy interfaces by implementing all methods
* Zero value: nil
Implicit Implementation
type Dog struct{} func (d Dog) Speak() string { return "Woof!" } var s Speaker = Dog{} // Dog satisfies Speaker fmt.Println(s.Speak()) // "Woof!"
Rule: No explicit implements keyword - satisfaction is automatic.
Empty Interface (interface{})
Use Case: Accept any type
func logAnything(v interface{}) { fmt.Printf("%T: %v\n", v, v) } logAnything(42) // int: 42 logAnything("hello") // string: hello
Type Assertions
Check Concrete Type:
var s Speaker = Dog{} dog := s.(Dog) // Extract Dog
Safe Check:
if dog, ok := s.(Dog); ok { fmt.Println(dog.Speak()) }
Type Switches
Handle Multiple Types:
func describe(i interface{}) { switch v := i.(type) { case Dog: fmt.Println("Dog says:", v.Speak()) case int: fmt.Println("Integer:", v) default: fmt.Printf("Unknown type %T\n", v) } }
Common Interfaces
Built-in Examples:
type error interface { Error() string } type Stringer interface { String() string }
Usage:
func (d Dog) String() string { return "I'm a dog" } fmt.Println(Dog{}) // Calls String() automatically
Interface Values
Under the Hood:
* Dynamic type + value (or nil)
var s Speaker // nil interface s = Dog{} // type=Dog, value=Dog{}
Nil vs Nil Interface:
var d *Dog // nil concrete value var s Speaker = d // s != nil (has type *Dog)
Best Practices
- Keep interfaces small (1-3 methods)
- Name interfaces with -er suffixes (Reader, Writer)
- Compose interfaces:
type ReadWriter interface { Reader Writer }
Interface Pitfalls
Watch For:
* Nil pointer dereference:
var s Speaker s.Speak() // PANIC: nil interface
Accidental shadowing:var _ io.Writer = (*bytes.Buffer)(nil) // Compile-time check
Real-World Examples
HTTP Handler:
type Handler interface { ServeHTTP(ResponseWriter, *Request) }
Sorting:
sort.Interface { Len() int Less(i, j int) bool Swap(i, j int) }
Key Insight: Interfaces enable polymorphism and dependency injection in Go.