Is it possible to mark a potentially uninitialized variable as good without using unsafe or panicking?

Viewed 5254

Is it possible to explain to the compiler that the v variable is good at the line marked as 1 without using unsafe or code that may call panic!?

#[derive(PartialEq, Debug)]
enum Enum {
    V1,
    V2,
    V3,
}

fn main() {
    let e = Enum::V1;

    let mut v: i32;

    if e == Enum::V1 || e == Enum::V2 {
        v = 17; //some complex, costy expression
    }
    match e {
        Enum::V1 | Enum::V2 => {
            println!("Results: {}", v); //1
        }
        _ => {}
    }
}

The compiler reports:

error[E0381]: use of possibly uninitialized variable: `v`
  --> src/main.rs:18:37
   |
18 |             println!("Results: {}", v); //1
   |                                     ^ use of possibly uninitialized `v`

I have a complex expression to initialize v in my real code instead of 17, the type of v does not implement Default, and I only need v for the Enum::V1 and Enum::V2 cases.

In the real code I have separate branches for Enum::V1 and Enum::V2, and I can move v initialization there.

I want to make my code more clear and I don't want to use potentially bad things like unsafe or Option::unwrap

2 Answers
Related