typestar

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

  1. any and all stop as soon as the answer is known.
  2. position and find locate the first match.
  3. min_by_key, count and product reduce to one value.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Terminal operations, step 9 of 14 in Iterators & closures.

← Previous Next →