为什么即使我已分配了该变量的每个字段,编译器也为什么会对未初始化的变量发出警告? [英] Why does the compiler warn about an uninitialized variable even though I've assigned each field of that variable?
问题描述
我在匹配的每个可能括号中完全分配了名为x
的MyStruct
实例的字段:
I'm completely assigning the fields of the MyStruct
instance named x
in every possible brace of the match:
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
}
为什么编译器会返回以下错误?
Why does the compiler return the following error?
error[E0381]: use of possibly uninitialized variable: `x`
--> src/main.rs:37:5
|
37 | x
| ^ use of possibly uninitialized `x`
我认为这是一个已知问题(另请参见其相关问题).
I think this is a known issue (see also its related issue).
推荐答案
let x: MyStruct;
并未将x
设置为空值,而是声明了一个变量.您仍然需要为其分配一个值.
let x: MyStruct;
doesn't set x
to an empty value, it declares a variable. You still need to assign a value to it.
fn f(y: MyEnum) -> MyStruct {
let x;
match y {
MyEnum::One => {
x = MyStruct { a: 1, b: 1 };
}
MyEnum::Two => {
x = MyStruct { a: 2, b: 2 };
}
MyEnum::Three => {
x = MyStruct { a: 3, b: 3 };
}
}
x
}
换句话说,let x;
创建一个未绑定变量,即一个没有关联值的变量.因此,您以后需要绑定一些值.
In other words, let x;
creates an unbound variable, a variable which doesn't have a value associated with it. Thus you need to bind some value to it later.
如果您只想从函数中返回一个值,则可以利用以下事实:Rust中几乎每个语句都会产生一个值,而最后一个语句的值就是函数的返回值.
If you only want to return a value from the function, you can take advantage of the fact that almost every statement in Rust produces a value, and a value of the last statement is the return value of a function.
fn f(y: MyEnum) -> MyStruct {
use MyEnum::*;
let x = match y {
One => MyStruct { a: 1, b: 1 },
Two => MyStruct { a: 2, b: 2 },
Three => MyStruct { a: 3, b: 3 },
};
x
}
如果您愿意的话,您也可以完全消除x
.
You can also completely eliminate x
, if you so choose.
fn f(y: MyEnum) -> MyStruct {
use MyEnum::*;
match y {
One => MyStruct { a: 1, b: 1 },
Two => MyStruct { a: 2, b: 2 },
Three => MyStruct { a: 3, b: 3 },
}
}
这篇关于为什么即使我已分配了该变量的每个字段,编译器也为什么会对未初始化的变量发出警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!