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

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  
主站蜘蛛池模板: 宜兰县| 白河县| 临夏市| 吴旗县| 义马市| 铜山县| 万荣县| 拉孜县| 武乡县| 泸西县| 长白| 新田县| 尼玛县| 辽中县| 日照市| 杂多县| 安图县| 遂溪县| 三亚市| 庄浪县| 申扎县| 隆林| 门源| 札达县| 康马县| 神木县| 宾川县| 阳春市| 淮南市| 滨州市| 绍兴县| 兰溪市| 额济纳旗| 高州市| 鄄城县| 武强县| 信宜市| 广宗县| 敦化市| 定结县| 湘潭市|