RsRust
IntermediateLesson 11 of 16

Traits & Generics – Rust

Describing shared behavior and writing code for many types.

A trait describes behavior that types can implement, comparable to interfaces but with default implementations. In Rust, traits take the place of inheritance.

trait Tier {
    fn name(&self) -> String;
    fn sprich(&self) -> String {                       // default implementation
        format!("{} makes a sound", self.name())
    }
}

struct Hund;
struct Katze;

impl Tier for Hund {
    fn name(&self) -> String { "Dog".into() }
    fn sprich(&self) -> String { "Woof!".to_string() }
}
impl Tier for Katze {
    fn name(&self) -> String { "Cat".into() }
}

fn vorstellen(t: &impl Tier) {
    println!("{}", t.sprich());
}

fn main() {
    vorstellen(&Hund);     // Woof!
    vorstellen(&Katze);    // Cat makes a sound
}

Generics let you write a function or type for many types. With trait bounds you specify what the type must be able to do. The compiler generates a separate, optimized version for every type used (monomorphization), with no runtime cost.

fn groesstes<T: PartialOrd + Copy>(liste: &[T]) -> T {
    let mut g = liste[0];
    for &x in liste {
        if x > g {
            g = x;
        }
    }
    g
}

struct Stapel<T> {
    elemente: Vec<T>,
}
impl<T> Stapel<T> {
    fn neu() -> Self { Stapel { elemente: Vec::new() } }
    fn push(&mut self, x: T) { self.elemente.push(x); }
    fn pop(&mut self) -> Option<T> { self.elemente.pop() }
}

fn main() {
    println!("{} {}", groesstes(&[3, 9, 2]), groesstes(&[1.5, 0.2]));   // 9 1.5
    let mut s = Stapel::neu();
    s.push("a");
    s.push("b");
    println!("{:?} {:?}", s.pop(), s.pop());     // Some("b") Some("a")
}

With many bounds the signature gets hard to read, and that is when you use a where clause. The most important standard traits include Display, Debug, Clone, Copy, PartialEq, Default, From/Into, and Iterator. Even operators are traits:

use std::fmt::Display;
use std::ops::Add;

fn zeige_summe<T>(a: T, b: T) -> String
where
    T: Add<Output = T> + Display + Copy,
{
    format!("{} + {} = {}", a, b, a + b)
}

#[derive(Debug, Clone, Copy, PartialEq)]
struct V2 { x: i32, y: i32 }

impl Add for V2 {
    type Output = V2;
    fn add(self, o: V2) -> V2 { V2 { x: self.x + o.x, y: self.y + o.y } }
}

fn main() {
    println!("{}", zeige_summe(2, 3));                       // 2 + 3 = 5
    println!("{:?}", V2 { x: 1, y: 2 } + V2 { x: 10, y: 20 });   // V2 { x: 11, y: 22 }
}
TipWith impl Trait in the return type you can return “some type that satisfies trait X”, e.g. iterators or closures, without writing out the long type.
WarningOrphan rule: you may only implement a trait for a type if either the trait or the type comes from your own crate. Display for Vec<i32> is therefore not allowed; wrap the type in a newtype.