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

  • Learning Rust
  • Paul Johnson Vesa Kaihlavirta
  • 245字
  • 2021-07-02 23:07:24

Using enumerate

A loop condition can also be more complex, using multiple conditions and variables. For example, the for loop can be tracked using enumerate. This will keep track of how many times the loop has executed, as shown here:

for(i, j) in (10..20).enumerate() 
{ 
     println!("loop has executed {} times. j = {}", i, j); 
} 

The following is the output:

Say we have an array that we need to iterate over to obtain the values. Here, the enumerate method can be used to obtain the value of the array members. The value returned in the condition will be a reference, so a code such as the one shown in the following example will fail to execute (line is a & reference whereas an i32 is expected):

// 04/enumerate/src/main.rs
fn main() { let my_array: [i32; 7] = [1i32,3,5,7,9,11,13]; let mut value = 0i32; for(_, line) in my_array.iter().enumerate() { value += line; } println!("{}", value); }

This can be simply converted back from the reference value, as follows:

for(_, line) in my_array.iter().enumerate() 
    { 
       value += *line; 
    } 

The iter().enumerate() method can equally be used with the Vec type (or any other type that implements the iterator trait), as shown in the following code:

// 04/arrayloop/src/main.rs
fn main() { let my_array = vec![1i32,3,5,7,9,11,13]; let mut value = 0i32; for(_,line) in my_array.iter().enumerate() { value += *line; } println!("{}", value); }

In both cases, the value given at the end will be 49, as shown in the following screenshot:

主站蜘蛛池模板: 德庆县| 长岭县| 衡阳市| 甘肃省| 陆川县| 兴城市| 罗城| 米易县| 台州市| 武穴市| 新河县| 兴仁县| 徐汇区| 台北县| 新宾| 勐海县| 游戏| 宁津县| 郸城县| 乌恰县| 鄂伦春自治旗| 鹿泉市| 双辽市| 彭州市| 那曲县| 开阳县| 砚山县| 岳普湖县| 宣化县| 满城县| 时尚| 垣曲县| 东乡族自治县| 当雄县| 遂平县| 多伦县| 大荔县| 南充市| 苍溪县| 海兴县| 沙洋县|