- 不可变的变量
Rust编程语言和其他的编程语言不同,它的变量初始化之后默认是不可以改变它的赋值的。这是Rust编程语言独有的特性。
rust
fn main() {
let x = 5;
println!("x的值是: {}", x);
x = 6;
println!("x的值是: {}", x);
}
如果运行上面的代码,系统会提示如下的错误信息:
bash
error[E0384]: cannot assign twice to immutable variable `x`
--> src\main.rs:4:5
|
2 | let x = 5;
| - first assignment to `x`
3 | println!("x的值是: {}", x);
4 | x = 6;
| ^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
2 | let mut x = 5;
| +++
For more information about this error, try `rustc --explain E0384`.
error: could not compile `lession_01_01` (bin "lession_01_01") due to 1 previous error
上面的信息告诉我们对不可变的变量x进行了两次赋值,如果需要更改x的值,需要使用mut修饰符来对x变量进行修改。即:let mut x = 5;
通过上面的代码运行,我们可以获知下面一些信息:
- 变量的定义语法:let 变量名称:变量类型 = 变量初始化值。
- 变量默认是不可修改的。
- 如果变量需要更改为可变的,需要再变量名称前面增加修饰符"mut"。即:let mut 变量名称:变量类型 = 变量初始化值。
修改上面的代码,使变量x更改为可以修改的变量。
rust
fn main() {
let mut x = 5;
println!("x的值是: {}", x);
x = 6;
println!("x的值是: {}", x);
}
执行 cargo run 运行上面的代码,系统给出下面的结果:
bash
Compiling lession_01_02 v0.1.0 (D:\projects\rust\rust_learn\lession_01_02)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.70s
Running `target\debug\lession_01_02.exe`
x的值是: 5
x的值是: 6
系统没有报错,并给出了正确的响应。