Non-mut variables is mutable leading to crash

Viewed 40

I ran across a weird case where Rust was telling me that I didn't need mut on a variable, even though I was clearly mutating it! After some fiddling around I managed to get the following code to compile which just looks broken.

fn main() {
    let x: u32;
    loop {
        match 1 {
            1 => {}
            _ => {
                x = 5;
                break;
            }
        }
    }
    dbg!(x);
}

Running it (playground) results in some kind of crash. What's going on here? Is this a compiler bug? I tried it on nightly and it still times out.

1 Answers

This also compiles:

let x: u32;

if false {
    x = 5;
}

As well as:

let x: u32;
x = 5;

As @trentcl mentions, this is deferred initialization, which is why it is accepted.

Related