@@ -57,14 +57,13 @@ for i in 0..nums.len() {
57
57
}
58
58
```
59
59
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:
63
62
64
63
``` rust
65
64
let nums = vec! [1 , 2 , 3 ];
66
65
67
- for num in nums . iter () {
66
+ for num in & nums {
68
67
println! (" {}" , num );
69
68
}
70
69
```
@@ -86,16 +85,17 @@ see it. This code works fine too:
86
85
``` rust
87
86
let nums = vec! [1 , 2 , 3 ];
88
87
89
- for num in nums . iter () {
88
+ for num in & nums {
90
89
println! (" {}" , * num );
91
90
}
92
91
```
93
92
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.
99
99
100
100
So, now that we've established that ranges are often not what you want, let's
101
101
talk about what you do want instead.
@@ -230,9 +230,9 @@ let nums = (1..100).collect::<Vec<i32>>();
230
230
Now, ` collect() ` will require that the range gives it some numbers, and so
231
231
it will do the work of generating the sequence.
232
232
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:
236
236
237
237
``` rust
238
238
let nums = [1 , 2 , 3 ];
0 commit comments