Skip to content

Commit 6532d2f

Browse files
committed
auto merge of #12161 : aepsil0n/rust/docs/for-loop, r=alexcrichton
I just started learning Rust and the absence of an explanation of the for-loop in the beginning really bugged me about the tutorial. Hence I simply added these lines, where I would have expected them. I know that there is something later on in the section on traits. However, this simple iteration scheme feels like something that you should be aware of right away.
2 parents 1366e04 + 68c960a commit 6532d2f

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/doc/tutorial.md

+26
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,32 @@ loop {
582582
This code prints out a weird sequence of numbers and stops as soon as
583583
it finds one that can be divided by five.
584584

585+
There is also a for-loop that can be used to iterate over a range of numbers:
586+
587+
~~~~
588+
for n in range(0, 5) {
589+
println!("{}", n);
590+
}
591+
~~~~
592+
593+
The snippet above prints integer numbers under 5 starting at 0.
594+
595+
More generally, a for loop works with anything implementing the `Iterator` trait.
596+
Data structures can provide one or more methods that return iterators over
597+
their contents. For example, strings support iteration over their contents in
598+
various ways:
599+
600+
~~~~
601+
let s = "Hello";
602+
for c in s.chars() {
603+
println!("{}", c);
604+
}
605+
~~~~
606+
607+
The snippet above prints the characters in "Hello" vertically, adding a new
608+
line after each character.
609+
610+
585611
# Data structures
586612

587613
## Structs

0 commit comments

Comments
 (0)