-
Notifications
You must be signed in to change notification settings - Fork 13.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Explained the difference between ownership iteration and reference iteration #32002
Changes from all commits
9bf73d2
a3c9afa
2dc723d
d2df551
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -115,6 +115,36 @@ for i in v { | |
} | ||
``` | ||
|
||
Note: You cannot use the vector again once you have iterated by taking ownership of the vector. | ||
You can iterate the vector multiple times by taking a reference to the vector whilst iterating. | ||
For example, the following code does not compile. | ||
|
||
```rust,ignore | ||
let mut v = vec![1, 2, 3, 4, 5]; | ||
|
||
for i in v { | ||
println!("Take ownership of the vector and its element {}", i); | ||
} | ||
|
||
for i in v { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. and between these two fors |
||
println!("Take ownership of the vector and its element {}", i); | ||
} | ||
``` | ||
|
||
Whereas the following works perfectly, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. and above here |
||
|
||
```rust | ||
let mut v = vec![1, 2, 3, 4, 5]; | ||
|
||
for i in &v { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. and between this let and for |
||
println!("This is a reference to {}", i); | ||
} | ||
|
||
for i in &v { | ||
println!("This is a reference to {}", i); | ||
} | ||
``` | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. and below here |
||
|
||
Vectors have many more useful methods, which you can read about in [their | ||
API documentation][vec]. | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
and between this let and for