mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-01-31 11:01:46 +02:00
Iterate over array ref instead of array. (#1081)
This revises the example to iterate over `&array` to dodge a few issues.
This commit is contained in:
parent
52284c7d13
commit
25d4281992
@ -22,7 +22,7 @@ keyword:
|
||||
fn main() {
|
||||
let array = [10, 20, 30];
|
||||
print!("Iterating over array:");
|
||||
for n in array {
|
||||
for n in &array {
|
||||
print!(" {n}");
|
||||
}
|
||||
println!();
|
||||
@ -79,4 +79,15 @@ implementation.
|
||||
The solution and the answer to the bonus section are available in the
|
||||
[Solution](solutions-morning.md#arrays-and-for-loops) section.
|
||||
|
||||
The use of the reference `&array` within `for n in &array` is a subtle
|
||||
preview of issues of ownership that will come later in the afternoon.
|
||||
|
||||
Without the `&`...
|
||||
* The loop would have been one that consumes the array. This is a
|
||||
change [introduced in the 2021
|
||||
Edition](https://doc.rust-lang.org/edition-guide/rust-2021/IntoIterator-for-arrays.html), and ...
|
||||
* since the array is also accessed in the second loop, an implicit
|
||||
array copy would have occured; since `i32` is a copy type, then
|
||||
`[i32; 3]` is also a copy type.
|
||||
|
||||
</details>
|
||||
|
Loading…
x
Reference in New Issue
Block a user