variables - 为什么修改未声明为可变的变量时编译器不报错?

标签 variables syntax compilation rust mutable

我安装了 Rust 1.13 并尝试了:

fn main() {
    let x: u32;
    x = 10; // no error?
}

当我编译这个文件时有一些警告,但没有错误。因为我没有将 x 声明为 mut,所以 x = 10; 不应该导致错误吗?

最佳答案

您所写的内容与:

let x: u32 = 10;

此后编译器将不允许您改变它:

let x: u32;
x = 10;
x = 0; // Error: re-assignment of immutable variable `x`

请注意,如果您尝试使用未初始化的变量,则会出现编译器错误:

let x: u32;
println!("{}", x); // Error: use of possibly uninitialized variable: `x`

如果您想根据运行时条件以不同方式初始化变量,则此功能非常有用。一个天真的例子:

let x: u32;
if condition {
    x = 1;   
} else if other_condition {
    x = 10;
} else {
    x = 100;
}

但如果有未初始化的可能性,它仍然会报错:

let x: u32;
if condition {
    x = 1;   
} else if other_condition {
    x = 10;
} // no else
println!("{:?}", x); // Error: use of possibly uninitialized variable: `x`

关于variables - 为什么修改未声明为可变的变量时编译器不报错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43519766/

相关文章:

compilation - 如何在Windows上的SCons中导出具有备用扩展名的程序

c++ - Visual Studio 中的 "multi-processor compilation"有什么缺点吗?

c - 每次调用父函数时是否重新分配 C 中的静态变量?

javascript - 如何在局部范围内重新定义对象变量

python - 定义实例变量时的最佳实践

mysql - 使用来自 codeigniter 的变量更新一条记录

javascript - 这个语法是如何工作的?

perl - Perl的postfix `for`语法在哪里记录?

c - 我在 VS 中收到预期的常量表达式错误,但它在 tutorialspoint 网络编译器上运行?

javascript - AngularJS:使用 ng-if 在指令中选择部分模板