2024-02-08 01:03:49 +05:30
|
|
|
# `for`
|
|
|
|
|
|
|
|
The [`for` loop](https://doc.rust-lang.org/std/keyword.for.html) iterates over
|
2024-02-22 07:49:49 -08:00
|
|
|
ranges of values or the items in a collection:
|
2024-02-08 01:03:49 +05:30
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
fn main() {
|
|
|
|
for x in 1..5 {
|
|
|
|
println!("x: {x}");
|
|
|
|
}
|
2024-02-22 07:49:49 -08:00
|
|
|
|
|
|
|
for elem in [1, 2, 3, 4, 5] {
|
|
|
|
println!("elem: {elem}");
|
|
|
|
}
|
2024-02-08 01:03:49 +05:30
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
<details>
|
|
|
|
|
2024-02-22 07:49:49 -08:00
|
|
|
- Under the hood `for` loops use a concept called "iterators" to handle
|
|
|
|
iterating over different kinds of ranges/collections. Iterators will be
|
|
|
|
discussed in more detail later.
|
2024-05-29 13:08:06 -04:00
|
|
|
- Note that the first `for` loop only iterates to `4`. Show the `1..=5` syntax
|
|
|
|
for an inclusive range.
|
2024-02-08 01:03:49 +05:30
|
|
|
|
|
|
|
</details>
|