Iterating over an inclusive range
We begin the chapter with a small feature that can make your code a bit more readable. The inclusive range syntax (..=
) will create a range up to a value including it. This helps you eliminate ugly instances of things like n .. m+1
by rewriting them as n ..= m
.
How to do it...
- Create a Rust project to work on during this chapter with
cargo new chapter-ten
. - Navigate into the newly-created
chapter-ten
folder. For the rest of this chapter, we will assume that your command line is currently in this directory. - Delete the generated
lib.rs
file, as we are not creating a library. - Inside the
src
folder, create a new folder calledbin
. - In the
src/bin
folder, create a file calledinclusive_range.rs
. - Add the following code, and run it with
cargo run --bin inclusive_range
:
1 #![feature(inclusive_range_syntax)] 2 3 fn main() { 4 // Retrieve the entire alphabet in lower and uppercase: 5 let alphabet: Vec<_> = (b'A' .. b'z' + 1) // Start as u8 6 .map...