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?
>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
}