diff --git a/src/references/solution.md b/src/references/solution.md index f7b469b42b6d..d1fe2253436e 100644 --- a/src/references/solution.md +++ b/src/references/solution.md @@ -4,6 +4,18 @@ {{#include exercise.rs:solution}} ``` +This solution highlights the difference between shared and mutable references: + +- **Shared References (`&`):** `magnitude` needs to read the vector components + but not modify them, so it takes a shared reference (`&[f64; 3]`). +- **Mutable References (`&mut`):** `normalize` modifies the vector in place, so + it requires an exclusive mutable reference (`&mut [f64; 3]`). +- **Dereferencing:** In the `normalize` loop, `item` is a `&mut f64`. To modify + the actual value, we must dereference it using `*item`. +- **Iteration:** When we iterate over a reference to an array (like `vector`), + the iterator yields references to the elements. In `magnitude`, `coord` is + `&f64`. In `normalize`, `item` is `&mut f64`. +
- Note that in `normalize` we were able to do `*item /= mag` to modify each