← Вернуться к курсу: Rust from scratch

Generics and trait bounds

Видео скоро появится

Imagine you need a function that returns the largest of a list of i32, another for a list of f64 and another for char. The code would be identical, only the type changes. Generics solve this: you write the code once with a type parameter, usually called T, and the compiler adapts it to each concrete type. You have already used them without knowing: Vec<T>, Option<T>, Result<T, E> and HashMap<K, V> are generic types. Now you will learn to create your own.

Generic functions and bounds

You declare the parameter in angle brackets after the name: fn largest<T>(list: &[T]) -> T. But if you try to compare with > inside, the compiler complains: not all types can be ordered. You must promise it that T supports it through a trait bound: T: PartialOrd. To return the element by value we also need T to be copyable: T: PartialOrd + Copy. Bounds are documentation and checking at the same time, and the error messages tell you exactly which bound is missing.

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

fn describe<T>(value: T) -> String
where
    T: std::fmt::Debug + Clone,
{
    format!("{:?} (cloned: {:?})", value, value.clone())
}

fn main() {
    println!("{}", largest(&[3, 9, 4]));
    println!("{}", largest(&[1.5, 0.2]));
    println!("{}", largest(&['x', 'b', 'z']));
    println!("{}", describe(vec![1, 2]));
}

When the bounds grow, the where clause moves them to a separate line and keeps the signature readable, as in describe. One detail: the compiler generates a specialized copy of the function for each type you use (this is called monomorphization). That is why Rust generics are as fast as if you had written each version by hand, although they can increase the binary size slightly.

Generic structs and enums

Structs can also be generic: struct Pair<T> { first: T, second: T }. In impl you must repeat the parameter: impl<T> Pair<T>. You can give methods only to certain concrete types or with bounds, for example a largest method that exists only if T implements PartialOrd. With several parameters, like Pair<A, B>, each field can have a different type. Option<T> and Result<T, E> are simply generic enums defined in the standard library.

rust
use std::fmt::Display;

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

impl<T> Pair<T> {
    fn new(first: T, second: T) -> Self {
        Pair { first, second }
    }
}

// only available when T can be compared and printed
impl<T: PartialOrd + Display> Pair<T> {
    fn show_largest(&self) {
        if self.first >= self.second {
            println!("largest is first: {}", self.first);
        } else {
            println!("largest is second: {}", self.second);
        }
    }
}

struct Labeled<K, V> {
    key: K,
    value: V,
}

fn main() {
    Pair::new(3, 8).show_largest();
    Pair::new("pear", "apple").show_largest();

    let item = Labeled { key: "age", value: 30 };
    println!("{} = {}", item.key, item.value);

    let nothing: Option<String> = None;
    let found: Result<u8, String> = Ok(1);
    println!("{:?} {:?}", nothing, found);
}

Finally, remember that generics and traits work together: the parameter T says which type is used and the bound says what that type can do. When the compiler asks for a bound, do not see it as an obstacle but as a question: what operations does my function need on T? If you only read the value, maybe a reference is enough; if you compare it, PartialOrd; if you print it, Display or Debug. Start with no bounds, let the compiler tell you which are missing and add only those. That way your functions end up as general as possible.

rust
fn count_matches<T: PartialEq>(items: &[T], target: &T) -> usize {
    let mut n = 0;
    for item in items {
        if item == target {
            n += 1;
        }
    }
    n
}

struct Stack<T> {
    items: Vec<T>,
}

impl<T> Stack<T> {
    fn new() -> Self { Stack { items: Vec::new() } }
    fn push(&mut self, item: T) { self.items.push(item); }
    fn pop(&mut self) -> Option<T> { self.items.pop() }
    fn len(&self) -> usize { self.items.len() }
}

fn main() {
    println!("{}", count_matches(&[1, 2, 1, 3, 1], &1));
    println!("{}", count_matches(&["a", "b", "a"], &"a"));

    let mut s: Stack<&str> = Stack::new();
    s.push("x");
    s.push("y");
    println!("{:?} {}", s.pop(), s.len());
}

Проверьте себя

Вопрос 1 из 4

What does fn f<T: Copy>(x: T) mean?

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →