Generics vs Interfaces in Go

When to Use Which

Use interfaces to define behavior contracts and generics to create type-safe, reusable data structures in Go.

Use interfaces to define behavior contracts for polymorphism and generics to create reusable data structures that work with multiple types. Interfaces describe what a type can do, while generics describe how to handle data of specific types without losing type safety.

// Interface: Defines behavior (what it does)
type Reader interface {
    Read(p []byte) (n int, err error)
}

// Generic: Defines reusable structure (how it stores data)
type Stack[T any] struct {
    items []T
}

func (s *Stack[T]) Push(item T) {
    s.items = append(s.items, item)
}