docs / Getting Started / Generics

Generics

Generic functions and types are monomorphized at compile time — a specialized copy is emitted for each unique set of type arguments. No runtime cost.

use system.io

// Generic function — monomorphized per type
fn identity<T>(x T) T
    x

// Generic struct
struct Pair<T, U>
    first T
    second U

// Generic class
class Box<T>
    private value T

    fn init(v T)
        self.value = v

    fn get() T
        self.value

fn main()
    let n = identity(42)
    let s = identity("hello")

    let p = Pair<int, String>(first: 1, second: "one")
    println(f"{p.first}: {p.second}")    // 1: one

    let b = Box<int>(v: 99)
    println(f"{b.get()}")                // 99

Calling identity(42) and identity("hello") produces two separate compiled functions (identity_int, identity_string). Generic structs and classes work the same way — each unique instantiation gets its own compiled type.