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.
Generic Functions
Section titled “Generic Functions”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 = i32let text := identity("hello"); // T = strGeneric Structs
Section titled “Generic Structs”type Box<T> struct { .value: T,};
let int_box := Box<i32>{.value: 42};let str_box := Box<str>{.value: "hello"};Generic Interfaces
Section titled “Generic Interfaces”type Container<T> interface { get() -> T; set(value: T);};Multiple Type Parameters
Section titled “Multiple Type Parameters”type Pair<K, V> struct { .key: K, .value: V,};
let entry := Pair<str, i32>{.key: "age", .value: 30};Generic Methods
Section titled “Generic Methods”type Box<T> struct { .value: T,};
fn (b: Box<T>) get() -> T { return b.value;}