Go — Interfaces
Basic interface
package main
import "fmt"
type Stringer interface {
String() string
}
type Person struct {
Name string
Age int
}
func (p Person) String() string {
return fmt.Sprintf("%s (%d)", p.Name, p.Age)
}
func main() {
var s Stringer = Person{Name: "Alice", Age: 30}
fmt.Println(s.String())
}
Implicit implementation
Go interfaces are satisfied implicitly:
type Writer interface {
Write([]byte) (int, error)
}
// bytes.Buffer implements Writer without explicit declaration
Multiple interfaces
type Reader interface {
Read([]byte) (int, error)
}
type ReadWriter interface {
Reader
Writer
}
Empty interface
var x interface{} = "hello"
var y interface{} = 42
// Type assertion
s, ok := x.(string)
fmt.Println(s, ok)
Interface as parameter
func Print(v interface{}) {
fmt.Printf("%v\n", v)
}
// Or use generics
func PrintAll[T any](items []T) {
for _, item := range items {
fmt.Println(item)
}
}
Best practices
- Keep interfaces small (1-3 methods)
- Accept interfaces, return structs
- Define interfaces where they're used
- Use empty interface sparingly
Mini Practice
Write Go code that:
- Defines an interface and implements it
- Uses an interface as a function parameter
- Demonstrates implicit implementation
- Uses the empty interface with type assertion
Up Next
In the next lesson, you'll learn about Error Handling — Go's error patterns.
Related Topics
Frequently Asked Questions about Interfaces
What is Interfaces in Go?
Interfaces is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Interfaces?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Interfaces.
Why is Interfaces important in Go?
Interfaces is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.