Concepts

30.1 Concepts (Structural Type Constraints)

type
  Comparable = concept a, b
    (a < b) is bool
    (a == b) is bool

  Container[T] = concept c
    c.len is int
    for x in c: x is T

  Shape = concept s
    s.area() is float

proc maxOf[T: Comparable](xs: openArray[T]): T =
  result = xs[0]
  for x in xs: (if result < x: result = x)

proc totalArea(shapes: openArray[Shape]): float = ...

30.2 New-Style Concepts (Nim 2)

More predictable matching. Self refers to the matched type.

type
  Hashable = concept
    proc hash(x: Self): Hash
    proc `==`(a, b: Self): bool
  Stack[T] = concept
    proc push(s: var Self, x: T)
    proc pop(s: var Self): T

30.3 Use Cases

Generic algorithms with clear constraints, compile-time interfaces (static polymorphism), better error messages than unconstrained generics.

Combine with when T is MyConcept for compile-time dispatch.