官术网_书友最值得收藏!

The for loop

The for loops are slightly different from the same construct in C-like languages. In C, the for loops consist of three things: an initialization, a stopping condition, and a stepping instruction. Rust for loops are a bit higher-level though: they are for iterating through sequences.

Let's take a simple example to start with—a loop that goes from 0 to 10 and outputs the value:

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

We create a variable x that takes an element from the range (0..10), one by one, and does something with it. In Rust terminology, 0..10 is not only a variable but also an iterator, as it gives back a value from a series of elements.

This is obviously a very simple example. We can also define the iterator to work in the opposite direction. In C, you will expect something akin to for (i = 10; i > 0; --i). In Rust, we use the rev() method to reverse the iterator, as follows:

for x in (0..10).rev() 
{ 
    println!("{},", x); 
}  

It is worth noting that the range excludes the last number. So, for the previous example, the values outputted are 9 to 0; essentially, the program generates the output values from 0 to 10 and then outputs them in reverse.

The general syntax for the for loops is as follows:

for var in sequence
{ // do something }

The C# equivalent for the preceding code is as follows:

foreach(var t in conditionsequence) 
     // do something  
主站蜘蛛池模板: 卓资县| 宁都县| 滨海县| 南丰县| 中江县| 怀柔区| 上饶县| 封开县| 安宁市| 水富县| 太谷县| 萝北县| 瑞昌市| 江阴市| 布尔津县| 大丰市| 上虞市| 仪征市| 栾城县| 富蕴县| 桑日县| 南澳县| 新余市| 台南市| 新化县| 大同县| 合阳县| 封开县| 大邑县| 灵璧县| 隆昌县| 元氏县| 原阳县| 二手房| 井冈山市| 东乌| 灌南县| 吉首市| 平山县| 庄河市| 海口市|