Expected behavior of `for` loop in rust [duplicate]

戏子无情 提交于 2020-01-04 16:56:18

问题


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 from a (inclusive) to b (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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!