Watch 25 Star 65 Fork 17

hainuo / rust ebookRuby

Create your Gitee Account
Explore and code with more than 6 million developers,Free private repositories !:)
Sign up
This repository doesn't specify license. Without author's permission, this code is only for learning and cannot be used for other purposes.
Clone or download 2.18 KB
Copy Edit Web IDE Raw Blame History
hainuo authored 2015-07-08 22:38 . 语法变量引用

% for Loops for循环语句

The for loop is used to loop a particular number of times. Rust’s for loops work a bit differently than in other systems languages, however. Rust’s for loop doesn’t look like this “C-style” for loop:


for (x = 0; x < 10; x++) {
    printf( "%d\n", x );

Instead, it looks like this:


for x in 0..10 {
    println!("{}", x); // x: i32

In slightly more abstract terms,


for var in expression {

The expression is an iterator. The iterator gives back a series of elements. Each element is one iteration of the loop. That value is then bound to the name var, which is valid for the loop body. Once the body is over, the next value is fetched from the iterator, and we loop another time. When there are no more values, the for loop is over.


In our example, 0..10 is an expression that takes a start and an end position,and gives an iterator over those values. The upper bound is exclusive, though,so our loop will print 0 through 9, not 10.

在我们的例子中,0..10 是一个表达式,有一个开始和一个结束位置,并且给处包含他们的迭代器。由于上线是排他性的,所以我们的循环将打印从09,不包含10.

Rust does not have the “C-style” for loop on purpose. Manually controlling each element of the loop is complicated and error prone, even for experienced C developers.


Comment ( 0 )

Sign in for post a comment