Go - Interfaces
Beginner 10/10
Teacher 10/10
Architect 10/10
Implicit Implementation
type Stringer interface{ String() string }
type User struct{ Name string }
func (u User) String() string { return u.Name }
func Print(s fmt.Stringer){ fmt.Println(s.String()) }
Interface Composition
type ReadWriteCloser interface{
io.Reader
io.Writer
io.Closer
}
Tips
- Depend on small interfaces; accept interfaces, return concrete types.
- Use interface values sparingly in hot paths.
Common errors
- Returning interfaces from constructors—prefer returning concrete types and accept interfaces.
- Nil interfaces vs typed nil: a
nil
interface value has no dynamic type; beware comparisons.
Practice
- Define a small interface (e.g.,
Sayer
) and implement it for two distinct concrete types. - Write a function that accepts your interface and works with both types.
Quick quiz
- How does a type implement an interface in Go?