impl Trait in Rust
Anonymous types in signatures: any argument that fits, any return that satisfies.
fn total(values: impl IntoIterator<Item = i32>) -> i32 {
values.into_iter().sum()
}
fn evens(limit: i32) -> impl Iterator<Item = i32> {
(0..limit).filter(|n| n % 2 == 0)
}
fn adder(step: i32) -> impl Fn(i32) -> i32 {
move |n| n + step
}
fn main() {
println!("{}", total(vec![1, 2, 3]));
println!("{:?}", evens(10).collect::<Vec<i32>>());
let add_five = adder(5);
println!("{}", add_five(37));
}
How it works
- In argument position it is shorthand for a bound.
- In return position it hides the concrete type.
- It is how closures and iterators get returned.
Keywords and builtins used here
FnIntoIteratorIteratorVecadderevensfni32implletmainmovetotal
The run, in numbers
- Lines
- 18
- Characters to type
- 397
- Tokens
- 154
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 88 seconds.
Step 4 of 4 in Generics, step 7 of 19 in Traits & generics.