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
- The implementor picks the type, the caller does not.
Self::Outputnames it inside the trait.Iterator::Itemis the associated type you already use.
Keywords and builtins used here
CounterOptionOutputSelfSomeStringVecWordsfnforimplmainparseselfstrstructtraittypeusize
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.
Step 3 of 3 in Traits, step 3 of 19 in Traits & generics.