Loops
8 min · Rust
Repeat work without writing it out a hundred times.
Enemy 1 of 5
Loops let you repeat a block of code without copy-pasting it. Rust's for loop is built to walk over a sequence of values — most commonly a range, written start..end. for i in 0..3 { ... } runs the loop body three times, with i taking the values 0, then 1, then 2 in turn.
The important detail is that 0..3 is a half-open range: it includes the start (0) but excludes the end (3). This is the same convention used by most modern languages' array indexing and is genuinely useful once it clicks — the number of iterations is simply end minus start, with no need to mentally add or subtract one. If you do want the end value included, Rust also offers an inclusive range with three dots: 0..=3 would include 3 as well.
Compared to the classic C-style for (int i = 0; i < 3; i++) loop, Rust's for i in 0..3 reads more like plain English and there's no way to accidentally write the wrong stop condition or forget to increment — the range handles all of that for you.
Loading editor...