..= for inclusive ranges

Since well before Rust 1.0, you’ve been able to create exclusive ranges with.. like this:
1. for i in 1..3 {
2. println!("i: {}", i);
3. }
This will print i: 1 and then i: 2. Today, you can now create aninclusive range, like this:
2. #![allow(unused_variables)]
3. fn main() {
4. for i in 1..=3 {
5. println!("i: {}", i);
6. }
7. }
This will print i: 1 and then i: 2 like before, but also i: 3; thethree is included in the range. Inclusive ranges are especially useful if youwant to iterate over every possible value in a range. For example, this is asurprising Rust program:
1. fn takes_u8(x: u8) {
2. // ...
3. }
5. fn main() {
6. for i in 0..256 {
7. println!("i: {}", i);
8. takes_u8(i);
9. }
10. }
What does this program do? The answer: it fails to compile. The error we getwhen compiling has a hint:
1. error: literal out of range for u8
2. --> src/main.rs:6:17
3. |
4. 6 | for i in 0..256 {
5. | ^^^
6. |
7. = note: #[deny(overflowing_literals)] on by default
That’s right, since i is a u8, this overflows, and the compiler producesan error.
We can do this with inclusive ranges, however:
1. fn takes_u8(x: u8) {
2. // ...
3. }
5. fn main() {
6. for i in 0..=255 {
7. println!("i: {}", i);
8. takes_u8(i);
9. }
10. }
This will produce those 256 lines of output you might have been expecting.
