typestar

Associated types in Rust

When a trait has one type per implementor, an associated type beats a parameter.

trait Parser {
    type Output;

    fn parse(&self, raw: &str) -> Option<Self::Output>;
}

struct Counter;
struct Words;

impl Parser for Counter {
    type Output = usize;

    fn parse(&self, raw: &str) -> Option<usize> {
        Some(raw.len())
    }
}

impl Parser for Words {
    type Output = Vec<String>;

    fn parse(&self, raw: &str) -> Option<Vec<String>> {
        Some(raw.split_whitespace().map(String::from).collect())
    }
}

fn main() {
    println!("{:?}", Counter.parse("four"));
    println!("{:?}", Words.parse("one two"));
}

How it works

  1. The implementor picks the type, the caller does not.
  2. Self::Output names it inside the trait.
  3. Iterator::Item is the associated type you already use.

Keywords and builtins used here

The run, in numbers

Lines
29
Characters to type
492
Tokens
161
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 97 seconds.

Type this snippet

Step 3 of 3 in Traits, step 3 of 19 in Traits & generics.

← Previous Next →