..= for inclusive ranges

Minimum Rust version: 1.26

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:

  1. #![allow(unused_variables)]
  2. fn main() {
  3. for i in 1..=3 {
  4. println!("i: {}", i);
  5. }
  6. }

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. }
  4. fn main() {
  5. for i in 0..256 {
  6. println!("i: {}", i);
  7. takes_u8(i);
  8. }
  9. }

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. }
  4. fn main() {
  5. for i in 0..=255 {
  6. println!("i: {}", i);
  7. takes_u8(i);
  8. }
  9. }

This will produce those 256 lines of output you might have been expecting.