我完全分配在比賽的每一個可能的支柱名爲x
的MyStruct
實例字段:爲什麼編譯器會警告有關未初始化的變量,即使我已經分配了該變量的每個字段?
enum MyEnum {
One,
Two,
Three,
}
struct MyStruct {
a: u32,
b: u32,
}
fn main() {
f(MyEnum::One);
f(MyEnum::Two);
f(MyEnum::Three);
}
fn f(y: MyEnum) -> MyStruct {
let mut x: MyStruct;
match y {
MyEnum::One => {
x.a = 1;
x.b = 1;
}
MyEnum::Two => {
x.a = 2;
x.b = 2;
}
MyEnum::Three => {
x.a = 3;
x.b = 3;
}
}
x
}
爲什麼編譯器返回下面的錯誤?
error[E0381]: use of possibly uninitialized variable: `x`
--> src/main.rs:37:5
|
37 | x
| ^use of possibly uninitialized `x`
我認爲這是a known issue(另見它的相關問題)。
'match'可以用在表達式上下文中;它可以作爲最後一個用作返回值的表達式,或者作爲'let x = match {...};'的右邊 - 這完全避免了你的問題(但嚴格地說並不是你的問題的答案) 。 – Stefan