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 {
|
2025-02-24 17:12:56 +03:00
|
|
|
dbg!(x);
|
2024-02-08 01:03:49 +05:30
|
|
|
}
|
2024-02-22 07:49:49 -08:00
|
|
|
|
2025-02-05 16:09:56 -08:00
|
|
|
for elem in [2, 4, 8, 16, 32] {
|
2025-02-24 17:12:56 +03:00
|
|
|
dbg!(elem);
|
2024-02-22 07:49:49 -08:00
|
|
|
}
|
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>
|