Skip to content

Generics

Generic Functions

wyn
fn max<T>(a: T, b: T) -> T {
    if a > b { return a }
    return b
}

bigger = max(10, 20)        // 20
larger = max(3.14, 2.71)    // 3.14

Generic Structs

Structs with type parameters:

wyn
struct Pair<T> {
    first: T
    second: T
}

p = Pair { first: 10, second: 20 }
print(p.first.to_string())   // 10
print(p.second.to_string())  // 20

// Field access and expressions
sum = p.first + p.second    // 30

Mixed generic and concrete fields:

wyn
struct Box<T> {
    value: T
    label: string
}

b = Box { value: 42, label: "answer" }
print(b.label)  // answer

Built-in Generic Types

wyn
// Result<T> - success or error
fn safe_div(a: int, b: int) -> Result<int> {
    if b == 0 { return Err("division by zero") }
    return Ok(a / b)
}

// Option<T> - present or absent
fn find(arr: [int], target: int) -> Option<int> {
    for i in 0..arr.len() {
        if arr[i] == target { return Some(i) }
    }
    return None
}

See Also

MIT License - v1.21.0