Explain container iteration in the loop tutorial
As suggested by @pnkfelix in #12161, this extends the examples by a for-loop that iterates over a string as an example for container iteration.
This commit is contained in:
parent
fbadb36c2b
commit
68c960a8bb
1 changed files with 16 additions and 2 deletions
|
|
@ -582,8 +582,7 @@ loop {
|
|||
This code prints out a weird sequence of numbers and stops as soon as
|
||||
it finds one that can be divided by five.
|
||||
|
||||
There is also a for-loop that can be used to iterate over a range of numbers
|
||||
(or, more generally, anything implementing the `Iterator` trait):
|
||||
There is also a for-loop that can be used to iterate over a range of numbers:
|
||||
|
||||
~~~~
|
||||
for n in range(0, 5) {
|
||||
|
|
@ -593,6 +592,21 @@ for n in range(0, 5) {
|
|||
|
||||
The snippet above prints integer numbers under 5 starting at 0.
|
||||
|
||||
More generally, a for loop works with anything implementing the `Iterator` trait.
|
||||
Data structures can provide one or more methods that return iterators over
|
||||
their contents. For example, strings support iteration over their contents in
|
||||
various ways:
|
||||
|
||||
~~~~
|
||||
let s = "Hello";
|
||||
for c in s.chars() {
|
||||
println!("{}", c);
|
||||
}
|
||||
~~~~
|
||||
|
||||
The snippet above prints the characters in "Hello" vertically, adding a new
|
||||
line after each character.
|
||||
|
||||
|
||||
# Data structures
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue