Skip to content

Commit cac3007

Browse files
committed
Rollup merge of rust-lang#22612 - jxcl:iter-replace, r=steveklabnik
r? @steveklabnik I've updated the iterators chapter to reflect the fact that you can now iterate over `for` loops without calling `.iter()`.
2 parents 310833c + 9f2b067 commit cac3007

File tree

1 file changed

+13
-13
lines changed

1 file changed

+13
-13
lines changed

src/doc/trpl/iterators.md

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,13 @@ for i in 0..nums.len() {
5757
}
5858
```
5959

60-
This is strictly worse than using an actual iterator. The `.iter()` method on
61-
vectors returns an iterator which iterates through a reference to each element
62-
of the vector in turn. So write this:
60+
This is strictly worse than using an actual iterator. You can iterate over vectors
61+
directly, so write this:
6362

6463
```rust
6564
let nums = vec![1, 2, 3];
6665

67-
for num in nums.iter() {
66+
for num in &nums {
6867
println!("{}", num);
6968
}
7069
```
@@ -86,16 +85,17 @@ see it. This code works fine too:
8685
```rust
8786
let nums = vec![1, 2, 3];
8887

89-
for num in nums.iter() {
88+
for num in &nums {
9089
println!("{}", *num);
9190
}
9291
```
9392

94-
Now we're explicitly dereferencing `num`. Why does `iter()` give us references?
95-
Well, if it gave us the data itself, we would have to be its owner, which would
96-
involve making a copy of the data and giving us the copy. With references,
97-
we're just borrowing a reference to the data, and so it's just passing
98-
a reference, without needing to do the copy.
93+
Now we're explicitly dereferencing `num`. Why does `&nums` give us
94+
references? Firstly, because we explicitly asked it to with
95+
`&`. Secondly, if it gave us the data itself, we would have to be its
96+
owner, which would involve making a copy of the data and giving us the
97+
copy. With references, we're just borrowing a reference to the data,
98+
and so it's just passing a reference, without needing to do the move.
9999

100100
So, now that we've established that ranges are often not what you want, let's
101101
talk about what you do want instead.
@@ -230,9 +230,9 @@ let nums = (1..100).collect::<Vec<i32>>();
230230
Now, `collect()` will require that the range gives it some numbers, and so
231231
it will do the work of generating the sequence.
232232

233-
Ranges are one of two basic iterators that you'll see. The other is `iter()`,
234-
which you've used before. `iter()` can turn a vector into a simple iterator
235-
that gives you each element in turn:
233+
Ranges are one of two basic iterators that you'll see. The other is `iter()`.
234+
`iter()` can turn a vector into a simple iterator that gives you each element
235+
in turn:
236236

237237
```rust
238238
let nums = [1, 2, 3];

0 commit comments

Comments
 (0)