Skip to content

Solution for exercise 9.6.1: Use references to a Dynamically Sized Slice instead of references to a Fixed-Size Array. #2848

@iurii-kyrylenko

Description

@iurii-kyrylenko

The following functions get references to a fixed-size array:

fn magnitude(vector: &[f64; 3]) -> f64 {

fn normalize(vector: &mut [f64; 3]) {

Don't think this is the best solution, especially after slices have just been discussed. The better option IMO would be to pass slices instead:

fn magnitude(vector: &[f64]) -> f64 {
    // ...
}

fn normalize(vector: &mut [f64]) {
    // ...
}

That way the functions accept any-dimensional vectors, e.g.

fn main() {
    println!(
        "Magnitude of a unit vector: {}",
        magnitude(&[0.0, 1.0, 0.0])
    );

    let mut v = [1.0, 2.0, 9.0];
    println!("Magnitude of {v:?}: {}", magnitude(&v));
    normalize(&mut v);
    println!("Magnitude of {v:?} after normalization: {}", magnitude(&v));

    let mut v4 = [1.0, 2.0, 3.0, 4.0];
    println!("4d vector: {v4:?}");
    normalize(&mut v4);
    println!("Normalized 4d vector: {v4:?}");
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions