一、变量和可变性
变量默认是不可改变的(immutable)。这是 Rust 提供给你的众多优势之一,让你得以充分利用 Rust 提供的安全性和简单并发性来编写代码。不过,你仍然可以使用可变变量。
文件名:src/main.rs
fn main() {
let x=5;
println!(" x 的值是: {}",x);
x=6;
println!(" x 的值是: {}",x);
}
保存并使用cargo run
运行,会看到报错信息
~/myrust/guessing_game master cargo run
Compiling guessing_game v0.1.0 (/Users/shuai/myrust/guessing_game)
error[E0384]: cannot assign twice to immutable variable `x`
--> src/main.rs:6:4
|
4 | let x=5;
| -
| |
| first assignment to `x`
| help: consider making this binding mutable: `mut x`
5 | println!(" x 的值是: {}",x);
6 | x=6;
| ^^^ cannot assign twice to immutable variable
For more information about this error, try `rustc --explain E0384`.
error: could not compile `guessing_game` due to previous error
尽管变量默认是不可变的,你仍然可以在变量名前添加 mut 来使其可变
fn main() {
let mut x=5;
println!(" x 的值是: {}",x);
x=6;
println!(" x 的值是: {}",x);
}
二、隐藏
我们可以定义一个与之前变量同名的新变量。Rustacean 们称之为第一个变量被第二个 隐藏(Shadowing) 了,这意味着当您使用变量的名称时,编译器将看到第二个变量。
fn main() {
let x = 5;
let x = x + 1;
{
let x = x * 2;
println!("The value of x in the inner scope is: {x}");
}
println!("The value of x is: {x}");
}
运行结果
✘ ~/myrust/guessing_game master cargo run
Compiling guessing_game v0.1.0 (/Users/shuai/myrust/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 0.34s
Running `target/debug/guessing_game`
The value of x in the inner scope is: 12
The value of x is: 6
mut 与隐藏的另一个区别是,当再次使用 let 时,实际上创建了一个新变量,我们可以改变值的类型,并且复用这个名字。
fn main() {
let spaces = " ";
let spaces = spaces.len();
}
然而,如果尝试使用 mut,将会得到一个编译时错误,如下所示:
fn main() {
let mut spaces = " ";
spaces = spaces.len();
}
上述代码会报如下错误:
~/myrust/guessing_game master cargo run
Compiling guessing_game v0.1.0 (/Users/shuai/myrust/guessing_game)
error[E0308]: mismatched types
--> src/main.rs:5:14
|
4 | let mut spaces = " ";
| ----- expected due to this value
5 | spaces = spaces.len();
| ^^^^^^^^^^^^ expected `&str`, found `usize`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `guessing_game` due to previous error