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
a..bexcludes the end,a..=bincludes it.revandstep_byare iterator adapters on the range.containstests membership without a comparison chain.
Keywords and builtins used here
Vecfnfori32inletmain
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.
Step 3 of 8 in Control flow, step 13 of 39 in Language basics.