Generic Data Structures
Building a generic Stack and Set
Why generic data structures?
Before generics, Go developers used interface{} slices (losing type safety) or generated code per type. Generics enable type-safe, reusable containers.
Generic Stack
A type-safe stack using a generic type:
type Stack[T any] struct{ items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
func (s *Stack[T]) Pop() (T, bool) {
if len(s.items)==0 { var z T; return z, false }
n := len(s.items)-1; v := s.items[n]; s.items = s.items[:n]; return v, true
}
func (s *Stack[T]) Len() int { return len(s.items) }All lessons in this course
- Type Parameters Syntax
- Constraints: comparable and interfaces
- Generic Data Structures
- Generics in Practice: Pitfalls