Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a variable assignment in a loop before a continue statement count as never read?

On the following code:

fn main() {
    let mut i: Option<i32> = None;

    let mut cond = true;
    while true && i.map_or(true, |x| x < 10) {
        if cond {
            cond = false;
            i = Some(0);
            continue;
        }
        i = Some(5);
    } 
}

I get the warning:

warning: value assigned to `i` is never read
 --> src/lib.rs:8:13
  |
8 |             i = Some(0);
  |             ^
  |
  = note: #[warn(unused_assignments)] on by default

This is very minimized (so please ignore for the moment that it'll loop forever), but shows the issue: the compiler seems to think that i from inside the if is overwritten by the outer assignment, which is clearly not the case due to the continue.

Am I missing something and have I introduced a bug of some description into the program, or is it the compiler's mistake?

like image 244
Michail Avatar asked Mar 06 '23 13:03

Michail


1 Answers

The compiler is not well aware of the flow break controls because of a bug. If you can, you should use an expression oriented syntax that is more idiomatic:

fn main() {
    let mut i = None;

    let mut cond = true;
    while true && i.map_or(true, |x| x < 10) {
        i = if cond {
            cond = false;
            Some(0)
        } else {
            Some(5)
        }
    } 
}

or create a custom iterator.

like image 163
Boiethios Avatar answered Apr 06 '23 11:04

Boiethios