Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why unused_assignment before if statment?

I have the following method and I get a unused_assignment warning for let mut res = 1.0:

fn my_func(pld: &f64, lambda: &[f64;NUMF]) -> [f64;NUMF] {
    let mut result = [0.0; NUMF];
    for i in 0..NUMF{
        let pdrel = pld / lambda[i];
        let mut res = 1.0;
        if pdrel >= 0.0 {
            res = 1.0;
        } else {
            res = 1.0 - (7.5 * pdrel.abs()).sqrt();
            if res >= 0.0 {
            } else {
                res = 0.0;
            }
        }
        result[i] = res;
    }
    result
}

I know I can #[allow(unused_assignment)]to avoid from showing. But how could I write more "correct" code to avoid the warning?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You never use the first assignment of res. That is why rustc is complaining. You assign it in all of the branches of the if-else statement below, therefore never reading the default 1.0 you assign it. You can just remove the assignment and rustc will stop giving you the warning:

fn my_func(pld: &f64, lambda: &[f64;NUMF]) -> [f64;NUMF] {
    let mut result = [0.0; NUMF];
    for i in 0..NUMF{
        let pdrel = pld / lambda[i];
        let mut res = 1.0;
        if pdrel >= 0.0 {
            res = 1.0;
        } else {
            res = 1.0 - (7.5 * pdrel.abs()).sqrt();
            if res >= 0.0 {
            } else {
                res = 0.0;
            }
        }
        result[i] = res;
    }
    result
}

Alternatively you can rely on the fact that each block has a return value in Rust, so you can return values from your if-else blocks directly. Then you don’t have to make res mutable, which you may prefer:

fn my_func(pld: &f64, lambda: &[f64;NUMF]) -> [f64;NUMF] {
    let mut result = [0.0; NUMF];
    for i in 0..NUMF{
        let pdrel = pld / lambda[i];
        
        let res = if pdrel >= 0.0 {
            1.0
        } else {
            let tmp = 1.0 - (7.5 * pdrel.abs()).sqrt();
            if tmp >= 0.0 {
                tmp
            } else {
                0.0
            }
        };
        
        result[i] = res;
    }
    result
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading