- Learning Rust
- Paul Johnson Vesa Kaihlavirta
- 254字
- 2021-07-02 23:07:24
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
- Embedded Linux Projects Using Yocto Project Cookbook
- 大學計算機基礎(第三版)
- UML和模式應用(原書第3版)
- The Modern C++ Challenge
- Docker技術入門與實戰(第3版)
- 數據結構習題精解(C語言實現+微課視頻)
- 深入淺出PostgreSQL
- MySQL從入門到精通(軟件開發視頻大講堂)
- Python全棧數據工程師養成攻略(視頻講解版)
- 一塊面包板玩轉Arduino編程
- 從零開始學C#
- Odoo 10 Implementation Cookbook
- Web性能實戰
- Python機器學習算法與應用
- .NET Standard 2.0 Cookbook