在此代码片段中,我将变量声明max为mut,但 rust-analyer 告诉我这是没有必要的。我删除了mut,代码仍然有效并运行。这是为什么?max我正在重新分配match 语句中的值。
fn validate_in_range_u32(value:u32, min:u32, max:u32) -> bool {
if value < min || value > max {
return false;
}
true
}
fn main() {
let day = 24;
let month = 8;
if !validate_in_range_u32(month, 1, 12) {
println!("Month is out of range (1-12)");
}
let max: u32;
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => max = 31,
2 => max = 28,
4 | 6 | 9 | 11 => max = 30,
_ => panic!("Should not happen"),
}
if !validate_in_range_u32(day, 1, max) {
println!("Day is out of range (1-{max})");
}
println!("It worked!");
}
Run Code Online (Sandbox Code Playgroud)
Mas*_*inn 10
这是为什么?我在 match 语句中重新分配 max 的值。
你实际上并没有重新分配,你只是在分配。
Rust 不进行隐式默认初始化,并且它跟踪“位置状态”,因此之后
let max: u32;
Run Code Online (Sandbox Code Playgroud)
max已定义但未初始化,如果您尝试读取它,您将收到编译错误:
error[E0381]: used binding `max` is possibly-uninitialized
Run Code Online (Sandbox Code Playgroud)
所以该match语句只是初始化它,Rust 不需要突变。
顺便说一句,就像 rust 中的大多数东西match都是表达式一样,所以更 rust-y 的风格是从 中返回值match并max就地初始化:
let max: u32;
Run Code Online (Sandbox Code Playgroud)
类型注释也不是必需的,因为validate_in_range_u32强加了u32.