Skip to content
Rust

Genéricos

Funções e structs genéricas.

#generics#generic

Code

rust
// Generic function
fn largest<T: PartialOrd>(list: &[T]) -> &T {
    let mut max = &list[0];
    for item in list {
        if item > max {
            max = item;
        }
    }
    max
}

// Generic struct
struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn x(&self) -> &T {
        &self.x
    }
}

// Multiple type parameters
struct Pair<K, V> {
    key: K,
    value: V,
}

// Generic method
impl<T: Clone> Point<T> {
    fn x_cloned(&self) -> T {
        self.x.clone()
    }
}

fn main() {
    let nums = vec![1, 2, 3, 4, 5];
    println!("Max: {}", largest(&nums));

    let p = Point { x: 1, y: 2 };
    println!("x = {}", p.x());

    let p2 = Point { x: 1.0, y: 2.0 };
    println!("x = {}", p2.x_cloned());
}