|
4 | 4 | {{#include exercise.rs:solution}} |
5 | 5 | ``` |
6 | 6 |
|
7 | | -<details> |
| 7 | +The solution demonstrates the fundamental distinction between shared and |
| 8 | +exclusive references: |
| 9 | + |
| 10 | +- **Shared References (`&`):** Used in `magnitude` because the function only |
| 11 | + reads the vector components. |
| 12 | +- **Exclusive References (`&mut`):** Required in `normalize` to modify the array |
| 13 | + elements in place. |
| 14 | +- **Explicit Dereferencing:** Inside `normalize`, `item` is an `&mut f64`. We |
| 15 | + use `*item` to access and modify the underlying value. |
8 | 16 |
|
9 | | -- Note that in `normalize` we were able to do `*item /= mag` to modify each |
10 | | - element. This is because we're iterating using a mutable reference to an |
11 | | - array, which causes the `for` loop to give mutable references to each element. |
| 17 | +<details> |
12 | 18 |
|
13 | | -- It is also possible to take slice references here, e.g., |
14 | | - `fn |
15 | | - magnitude(vector: &[f64]) -> f64`. This makes the function more general, |
16 | | - at the cost of a runtime length check. |
| 19 | +- **Iterating over References:** Iterating over `&vector` or `&mut vector` |
| 20 | + yields references to the elements. This is why `coord` is `&f64` and `item` |
| 21 | + is `&mut f64`. |
| 22 | +- **Arrays vs. Slices:** The functions are defined using array references |
| 23 | + (`&[f64; 3]`), which ensures the length is known at compile time. Using |
| 24 | + slices (`&[f64]`) would make the functions more flexible but would introduce |
| 25 | + a runtime length check or potential for panics if the slice has the wrong |
| 26 | + size. |
| 27 | +- **Method Call Ergonomics:** In `magnitude`, we can call `mag_squared.sqrt()` |
| 28 | + directly. In `normalize`, we pass `vector` (an `&mut [f64; 3]`) to |
| 29 | + `magnitude`, and Rust automatically downgrades the exclusive reference to a |
| 30 | + shared reference to match the signature. |
17 | 31 |
|
18 | 32 | </details> |
0 commit comments