From fbadb36c2bb53c40299744ff2c5cbc032a1ea7c7 Mon Sep 17 00:00:00 2001 From: Eduard Bopp Date: Mon, 10 Feb 2014 22:33:09 +0100 Subject: [PATCH 1/2] Document for-loop in tutorial section on loops --- src/doc/tutorial.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/doc/tutorial.md b/src/doc/tutorial.md index 73fec54fbcb60..a7e1b2b64c685 100644 --- a/src/doc/tutorial.md +++ b/src/doc/tutorial.md @@ -582,6 +582,18 @@ 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): + +~~~~ +for n in range(0, 5) { + println!("{}", n); +} +~~~~ + +The snippet above prints integer numbers under 5 starting at 0. + + # Data structures ## Structs From 68c960a8bb6b29c7e5e81ee4cefd8d135984b512 Mon Sep 17 00:00:00 2001 From: Eduard Bopp Date: Tue, 11 Feb 2014 15:27:10 +0100 Subject: [PATCH 2/2] 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. --- src/doc/tutorial.md | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/doc/tutorial.md b/src/doc/tutorial.md index a7e1b2b64c685..0d2a70b3af46d 100644 --- a/src/doc/tutorial.md +++ b/src/doc/tutorial.md @@ -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