Generics Cheatsheet

Basic Syntax

func FunctionName[T Constraint](param T) T { ... }

Constraints

  • any: Allows any type (alias for interface{}).
  • comparable: Built-in constraint for types that support == and !=.
  • Interface: Custom interface with methods (e.g., Stringer).

Type Lists

  • OR: int | float64 (Exactly these types).
  • Underlying: ~int (Any type with int as the base).

Generic Types

  • Structs: type Stack[T any] struct { items []T }
  • Interfaces: type Store[T any] interface { Save(T) }

Zero Value

var zero T
return zero

Key Rules

  • Generics work with functions, structs, and interfaces.
  • Methods cannot have their own type parameters (only the receiver type can be generic).
  • Use ~ if you want to support user-defined types (e.g., type MyID int).
  • Generics provide compile-time safety and avoid the performance cost of reflection or interface boxing.