typestar

Ranges in Rust

Ranges are values: iterate them, reverse them, step through them.

fn main() {
    let squares: Vec<i32> = (1..=5).map(|n| n * n).collect();
    println!("{:?}", squares);

    for n in (0..10).step_by(3) {
        print!("{n} ");
    }
    println!();

    for n in (1..4).rev() {
        print!("{n} ");
    }
    println!();

    println!("{}", (1..=12).contains(&7));
}

How it works

  1. a..b excludes the end, a..=b includes it.
  2. rev and step_by are iterator adapters on the range.
  3. contains tests membership without a comparison chain.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
254
Tokens
113
Three-star pace
85 tpm

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

Type this snippet

Step 3 of 8 in Control flow, step 13 of 39 in Language basics.

← Previous Next →