Skip to content

Commit dc18093

Browse files
committed
references: add explanatory commentary to solution
This commentary, written by Gemini, focuses on aspects of the solution that differ from the baseline languages (C/Java/Python), highlighting Rust-specific idioms and concepts.
1 parent 0867e24 commit dc18093

1 file changed

Lines changed: 22 additions & 8 deletions

File tree

src/references/solution.md

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,29 @@
44
{{#include exercise.rs:solution}}
55
```
66

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.
816

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>
1218

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.
1731

1832
</details>

0 commit comments

Comments
 (0)