rust - Is it possible to mark a potentially uninitialized variable as good without using unsafe or panicking? -
is possible explain compiler v
variable @ line marked 1
without using unsafe or code 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 complex expression initialize v
in real code instead of 17
, type of v
not implement default
, , need v
enum::v1
, enum::v2
cases.
in real code have separate branches enum::v1
, enum::v2
, , can move v
initialization there.
i want make code more clear , don't want use potentially bad things unsafe
or option::unwrap
the simple method initialize v
; it's single word , compiler can optimize away if unnecessary. in particular case, move both declaration , initialization inner scope of match, because isn't used anywhere else.
the cleaner thing make invalid case unrepresentable. here v
exists in cases v1
or v2
, if join 2 don't have name possibly uninitialized value.
#[derive(partialeq, debug)] enum enum { v1 { v: i32 }, v2 { v: i32 }, v3 } fn main() { let mut e = enum::v1 { v: 17 }; match e { enum::v1 {v} | enum::v2 {v} => { println!("results: {}", v);//1 } _ => {} } }
Comments
Post a Comment