Skip to content

Generics

A two-line generic identity function with explicit instantiation.

def identity[T](value: T) -> T:
return value
def main() -> i32:
let x: i32 = identity[i32](1)
return x

What’s worth noticing:

  • def identity[T](value: T) -> T:: single type parameter declared in brackets after the name.
  • identity[i32](1): instantiation is explicit at the call site. There is no inference of the T argument.
  • The compiler monomorphises each instantiation. identity[i32] and identity[bool] are separate, specialised functions in the final program.

This is the smallest illustration of the explicit-instantiation rule. For multi-parameter generics, see std.result’s unwrap_or[T, E].

IR-shape regression cases for identity[T] show zero overhead: the lowered code is bit-identical to a hand-written specialised function. See the Generics page for the rationale.