Rust has essentially three types of loops:
loop
is the simplest one—it just goes through a block of code again and again until one of the loop-breaking keywords is usedwhile
is like loop, but with a condition—the block of code is looped again and again as long as the condition is truefor
is different from the above two—it is for iterating through sequences
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...