修改未声明为可变的变量时,为什么编译器不报告错误? [英] Why doesn't the compiler report an error when a variable not declared as mutable is modified?

查看:126
本文介绍了修改未声明为可变的变量时,为什么编译器不报告错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我安装了Rust 1.13并尝试:

I installed Rust 1.13 and tried:

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

当我编译该文件时,会有一些警告,但没有错误.因为我没有将x声明为mut,所以x = 10;不会引起错误吗?

When I compiled this file there's some warnings, but there's no error. As I'm not declaring x as mut, shouldn't x = 10; cause an error?

推荐答案

您编写的内容与以下内容相同:

What you have written is identical to:

let x: u32 = 10;

此后,编译器将不允许您对其进行突变:

The compiler will not permit you to mutate it thereafter:

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

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

Note that it is a compiler error if you try to use an uninitialized variable:

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

如果您要根据运行时条件对变量进行不同的初始化,则此功能非常有用.一个简单的例子:

This feature can be pretty useful if you want to initialize the variable differently based on runtime conditions. A naive example:

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

但是,如果存在未初始化的可能性,仍然会出现错误:

But still it will still be an error if there is a possibility that it isn't initialized:

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

这篇关于修改未声明为可变的变量时,为什么编译器不报告错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆