How do I include the end value in a range?

Rust 1.26

As of Rust 1.26, you can use “inclusive ranges”:

fn main() {
    for i in 0..=26 {
        println!("{}", i);
    }
}

Rust 1.0 through 1.25

You need to add one to your end value:

fn main() {
    for i in 0..(26 + 1) {
        println!("{}", i);
    }
}

This will not work if you need to include all the values:


However, you cannot iterate over a range of characters:

error[E0277]: the trait bound `char: std::iter::Step` is not satisfied
 --> src/main.rs:2:14
  |
2 |     for i in 'a'..='z'  {
  |              ^^^^^^^^^ the trait `std::iter::Step` is not implemented for `char`
  |
  = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::ops::RangeInclusive<char>`

See Why can’t a range of char be collected? for solutions.

I would just specify the set of characters you are interested in:

static ALPHABET: &str = "abcdefghijklmnopqrstuvwxyz";

for c in ALPHABET.chars() {
    println!("{}", c);
}

Leave a Comment