FerrousPath

Level 3 · Systems· Lesson 4 of 11 · 30 min

Advanced traits

Associated types versus generics, generic associated types, higher-ranked bounds, coherence, sealed traits and extension traits.

Associated types versus type parameters

use std::ops::Mul;

#[derive(Debug, Clone, Copy)]
struct Metres(f64);
#[derive(Debug, Clone, Copy)]
struct SquareMetres(f64);

// A type PARAMETER (Rhs): one type can implement Mul for many right-hand sides.
impl Mul<f64> for Metres {
    type Output = Metres;             // an ASSOCIATED type: determined by (Self, Rhs)
    fn mul(self, k: f64) -> Metres { Metres(self.0 * k) }
}

impl Mul<Metres> for Metres {
    type Output = SquareMetres;
    fn mul(self, o: Metres) -> SquareMetres { SquareMetres(self.0 * o.0) }
}

fn main() {
    let side = Metres(3.0);
    println!("{:?} {:?}", side * 2.0, side * side);
}

Rule of thumb: inputs to the choice of implementation are type parameters; outputs are associated types. With an associated type, inference is unambiguous and users never have to name it.

Generic associated types

An associated type may itself be generic. The motivating example is a lending iterator, whose items borrow from the iterator itself — something Iterator cannot express, because Item has no way to mention the lifetime of the &mut self borrow.

trait LendingIterator {
    type Item<'a> where Self: 'a;
    fn next(&mut self) -> Option<Self::Item<'_>>;
}

/// Yields overlapping mutable windows — impossible with std's Iterator.
struct WindowsMut<'s, T> {
    slice: &'s mut [T],
    size: usize,
    pos: usize,
}

impl<'s, T> LendingIterator for WindowsMut<'s, T> {
    type Item<'a> = &'a mut [T] where Self: 'a;

    fn next(&mut self) -> Option<&mut [T]> {
        let window = self.slice.get_mut(self.pos..self.pos + self.size)?;
        self.pos += 1;
        Some(window)
    }
}

fn main() {
    let mut data = [1, 2, 3, 4, 5];
    let mut it = WindowsMut { slice: &mut data, size: 2, pos: 0 };
    while let Some(w) = it.next() {
        w[1] += w[0]; // running sum, in place
    }
    println!("{data:?}");
}

Each window must be released before the next next() call — the borrow checker enforces it, and that is exactly what makes overlapping &mut windows sound.

Higher-ranked trait bounds

Normally lifetime parameters are chosen by the caller. Sometimes a function needs a closure that works for any lifetime, because the function itself will create the references:

fn apply_to_local<F>(f: F) -> usize
where
    F: for<'a> Fn(&'a str) -> &'a str,
{
    let local = String::from("  padded  ");
    f(&local).len() // the borrow of `local` has a lifetime the caller could never name
}

fn main() {
    println!("{}", apply_to_local(|s| s.trim()));
}

for<'a> reads “for all 'a”. You rarely write it out: F: Fn(&str) -> &str is sugar for exactly this. It becomes visible in error messages (“implementation of FnOnce is not general enough”), and now you know what they mean.

Coherence and the orphan rule

Coherence is the property that for any type and trait there is at most one implementation in the whole program. The compiler enforces it with two checks:

  • Overlap: two impls in one crate must not apply to the same type. impl<T: Display> Foo for T and impl Foo for String overlap.
  • Orphan rule: an impl is allowed only if the trait is local, or a local type appears in a suitably “uncovered” position among the trait’s type arguments.

The precise orphan rule lets you write impl From<MyType> for Vec<u8> (a local type is a parameter of the foreign trait) but not impl<T> From<T> for Vec<u8>.

Because adding an impl may collide with someone else’s, a blanket impl in a library is a serious commitment: it prevents downstream crates — and your own future self — from writing more specific ones. There is no stable specialization.

Patterns built on traits

Extension traits

Add methods to foreign types by defining a trait and implementing it for them:

trait StrExt {
    fn word_count(&self) -> usize;
    fn title_case(&self) -> String;
}

impl StrExt for str {
    fn word_count(&self) -> usize {
        self.split_whitespace().count()
    }
    fn title_case(&self) -> String {
        self.split_whitespace()
            .map(|w| {
                let mut c = w.chars();
                c.next().map(|f| f.to_uppercase().chain(c).collect::<String>()).unwrap_or_default()
            })
            .collect::<Vec<_>>()
            .join(" ")
    }
}

fn main() {
    println!("{} {}", "the rust book".word_count(), "the rust book".title_case());
}

Sealed traits

mod sealed {
    pub trait Sealed {}
}

/// Implemented for the integer types this crate supports. Cannot be implemented outside it.
pub trait Word: sealed::Sealed {
    const BITS: u32;
}

impl sealed::Sealed for u32 {}
impl sealed::Sealed for u64 {}
impl Word for u32 { const BITS: u32 = 32; }
impl Word for u64 { const BITS: u32 = 64; }

fn bits<W: Word>() -> u32 { W::BITS }

fn main() {
    println!("{} {}", bits::<u32>(), bits::<u64>());
}

Outside code can use Word as a bound but cannot name sealed::Sealed to implement it.

Marker traits and auto traits

Traits with no methods encode properties: Copy, Send, Sync, Sized, Unpin. Auto traits (Send, Sync, Unpin) are implemented automatically when all fields implement them. Sized is an implicit bound on every type parameter; write T: ?Sized to accept unsized types such as str and dyn Trait.

Disambiguation

When two traits define the same method name, use fully qualified syntax: <Type as Trait>::method(&value).

Exercises

  1. Define trait Container { type Item; fn get(&self, i: usize) -> Option<&Self::Item>; fn first(&self) -> Option<&Self::Item> { self.get(0) } } and implement it for Vec<T> and for your own struct Repeat<T>(T).
  2. Write an extension trait on Iterator (trait IterExt: Iterator) that adds fn every_nth(self, n: usize) -> impl Iterator<Item = Self::Item> with a blanket impl.
  3. Explain, with reference to coherence, why impl<T> Display for Vec<T> is rejected in your crate, and show the newtype workaround.
  4. Implement LendingIterator for a struct that reads lines into one reused String buffer and lends out &str.

Check your understanding

Pick an answer to see the explanation.

  1. 1.When should a trait use an associated type instead of a type parameter?

  2. 2.What does for<'a> F: Fn(&'a str) -> &'a str express?

  3. 3.What is a sealed trait?

Key terms in this lesson

Finished the lesson and the exercises?