Skip to content

Pass slices to functions in exercise 9.6.1 (#2848) #2850

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/references/exercise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

// ANCHOR: solution
/// Calculate the magnitude of the given vector.
fn magnitude(vector: &[f64; 3]) -> f64 {
fn magnitude(vector: &[f64]) -> f64 {
let mut mag_squared = 0.0;
for coord in vector {
mag_squared += coord * coord;
Expand All @@ -23,7 +23,7 @@ fn magnitude(vector: &[f64; 3]) -> f64 {
}

/// Change the magnitude of the vector to 1.0 without changing its direction.
fn normalize(vector: &mut [f64; 3]) {
fn normalize(vector: &mut [f64]) {
let mag = magnitude(vector);
for item in vector {
*item /= mag;
Expand All @@ -38,5 +38,11 @@ fn main() {
println!("Magnitude of {v:?}: {}", magnitude(&v));
normalize(&mut v);
println!("Magnitude of {v:?} after normalization: {}", magnitude(&v));

// Normalize a 4d-vector
let mut v4 = [1.0, 2.0, 3.0, 4.0];
println!("4d-vector: {v4:?}");
normalize(&mut v4);
println!("Normalized 4d-vector: {v4:?}");
}
// ANCHOR_END: main
Loading