You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-06-18 23:27:34 +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:
@ -22,7 +22,7 @@ keyword:
|
|||||||
fn main() {
|
fn main() {
|
||||||
let array = [10, 20, 30];
|
let array = [10, 20, 30];
|
||||||
print!("Iterating over array:");
|
print!("Iterating over array:");
|
||||||
for n in array {
|
for n in &array {
|
||||||
print!(" {n}");
|
print!(" {n}");
|
||||||
}
|
}
|
||||||
println!();
|
println!();
|
||||||
@ -79,4 +79,15 @@ implementation.
|
|||||||
The solution and the answer to the bonus section are available in the
|
The solution and the answer to the bonus section are available in the
|
||||||
[Solution](solutions-morning.md#arrays-and-for-loops) section.
|
[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>
|
</details>
|
||||||
|
Reference in New Issue
Block a user