Generic Functions and Data Structures

Updated

October 31, 2026

Generic Functions and Data Structures

Generics allow writing flexible, reusable code with monomorphized zero runtime overhead.

#[derive(Debug)]
struct Pair<T> {
    first: T,
    second: T,
}

fn swap<T>(a: T, b: T) -> (T, T) {
    (b, a)
}

fn main() {
    let p = Pair { first: 10, second: 20 };
    let (x, y) = swap("hello", "world");
    println!("Pair: {:?}, Swapped: ({}, {})", p, x, y);
}