Asking questions of an iterator in Rust
The terminal methods that answer a question rather than build a collection.
fn main() {
let nums = [4, 8, 15, 16, 23, 42];
println!("{}", nums.iter().any(|n| *n > 40));
println!("{}", nums.iter().all(|n| n % 2 == 0));
println!("{:?}", nums.iter().position(|n| *n == 15));
println!("{:?}", nums.iter().find(|n| **n % 5 == 0));
println!("{:?}", nums.iter().min_by_key(|n| (**n - 20).abs()));
println!("{}", nums.iter().filter(|n| **n > 10).count());
println!("{}", (1..=5).product::<i32>());
}
How it works
anyandallstop as soon as the answer is known.positionandfindlocate the first match.min_by_key,countandproductreduce to one value.
Keywords and builtins used here
fni32letmain
The run, in numbers
- Lines
- 11
- Characters to type
- 416
- Tokens
- 208
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 125 seconds.
Step 1 of 3 in Terminal operations, step 9 of 14 in Iterators & closures.