{{#include exercise.rs:solution}}The solution demonstrates the fundamental distinction between shared and exclusive references:
- Shared References (
&): Used inmagnitudebecause the function only reads the vector components. - Exclusive References (
&mut): Required innormalizeto modify the array elements in place. - Explicit Dereferencing: Inside
normalize,itemis an&mut f64. We use*itemto access and modify the underlying value.
Details
- Iterating over References: Iterating over
&vectoror&mut vectoryields references to the elements. This is whycoordis&f64anditemis&mut f64. - Arrays vs. Slices: The functions are defined using array references
(
&[f64; 3]), which ensures the length is known at compile time. Using slices (&[f64]) would make the functions more flexible but would introduce a runtime length check or potential for panics if the slice has the wrong size. - Method Call Ergonomics: In
magnitude, we can callmag_squared.sqrt()directly. Innormalize, we passvector(an&mut [f64; 3]) tomagnitude, and Rust automatically downgrades the exclusive reference to a shared reference to match the signature.