2

I'm new to rust and I've question about the way the for loop.

fn main() {
    for x in 1 .. 10 {
        println!("x == {}", x);
    }
}

The output of the program is

x == 1
x == 2
x == 3
x == 4
x == 5
x == 6
x == 7
x == 8
x == 9

I was expecting for loop to execute and display x == 10 but it stopped at 9. Is this expected behavior

user51
  • 8,843
  • 21
  • 79
  • 158
  • 1
    the upper bound is exclusive, so it will not be in the output. Check the docs: https://doc.rust-lang.org/1.2.0/book/for-loops.html – blurfus Feb 25 '18 at 22:20

3 Answers3

4

The x..y syntax in Rust indicates a Range.

Ranges in Rust, like many other languages and libraries, have an exclusive upper-bound:

https://rustbyexample.com/flow_control/for.html

One of the easiest ways to create an iterator is to use the range notation a..b. This yields values from a (inclusive) to b (exclusive) in steps of one.

Dai
  • 141,631
  • 28
  • 261
  • 374
4

This is expected! The 0 .. 10 is an "exclusive range" meaning it does not include the upper bound. There is also an "inclusive range" syntax in the works which does include the upper bound, but it has not been released yet. The new syntax is being tracked in rust-lang/rust#28237.

For now you can make the loop include 10 by writing an exclusive range with 11 as the upper bound.

fn main() {
    for x in 1..11 {
        println!("x == {}", x);
    }
}

Or by starting at 0 and printing x + 1.

fn main() {
    for x in 0..10 {
        println!("x == {}", x + 1);
    }
}
dtolnay
  • 9,621
  • 5
  • 41
  • 62
2

Yes, this is expected. The end is not inclusive with when creating a range using ...

In patterns you can use ... for an inclusive range and there is an unstable feature that allows you to use ..= to create an inclusive range.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262