Skip to content
This feature is coming soon! Stay tuned for updates.

Generics

We use fixed types in our programs, but sometimes we want to write code that can operate on different types without duplicating it. Generics allow you to write flexible, reusable code that works with multiple types.

To define a generic function, we use angle brackets <T> to specify type parameters.

fn identity<T>(value: T) -> T {
return value;
}
let num := identity(42); // T = i32
let text := identity("hello"); // T = str
type Box<T> struct {
.value: T,
};
let int_box := Box<i32>{.value: 42};
let str_box := Box<str>{.value: "hello"};
type Container<T> interface {
get() -> T;
set(value: T);
};
type Pair<K, V> struct {
.key: K,
.value: V,
};
let entry := Pair<str, i32>{.key: "age", .value: 30};
type Box<T> struct {
.value: T,
};
fn (b: Box<T>) get() -> T {
return b.value;
}