问题
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
回答1:
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);
}
}
回答2:
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 froma(inclusive) tob(exclusive) in steps of one.
回答3:
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.
来源:https://stackoverflow.com/questions/48979080/expected-behavior-of-for-loop-in-rust