Skip to content

Commit 9bf73d2

Browse files
committed
Explained the difference between ownership iteration and reference iteration
1 parent 54fdae3 commit 9bf73d2

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/doc/book/vectors.md

+23
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,30 @@ for i in v {
114114
println!("Take ownership of the vector and its element {}", i);
115115
}
116116
```
117+
Note: You cannot use the vector again once you have iterated with ownership of the vector.
118+
You can iterate the vector multiple times with reference iteration. For example, the following
119+
code does not compile.
120+
```rust
121+
let mut v = vec![1, 2, 3, 4, 5];
122+
for i in v {
123+
println!("Take ownership of the vector and its element {}", i);
124+
}
125+
for i in v {
126+
println!("Take ownership of the vector and its element {}", i);
127+
}
128+
```
129+
Whereas the following works perfectly,
117130

131+
```rust
132+
let mut v = vec![1, 2, 3, 4, 5];
133+
for i in &v {
134+
println!("A mutable reference to {}", i);
135+
}
136+
137+
for i in &v {
138+
println!("A mutable reference to {}", i);
139+
}
140+
```
118141
Vectors have many more useful methods, which you can read about in [their
119142
API documentation][vec].
120143

0 commit comments

Comments
 (0)