fn main() {
let x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}
保存并使用 cargo run 運(yùn)行程序。應(yīng)該會(huì)看到一條錯(cuò)誤信息,如下輸出所示:
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
error[E0384]: cannot assign twice to immutable variable `x`
--> src/main.rs:4:5
|
2 | let x = 5;
| -
| |
| first assignment to `x`
| help: consider making this binding mutable: `mut x`
3 | println!("The value of x is: {x}");
4 | x = 6;
| ^^^^^ cannot assign twice to immutable variable
For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables` due to previous error
fn main() {
let mut x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}
現(xiàn)在運(yùn)行這個(gè)程序,出現(xiàn)如下內(nèi)容:
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
Finished dev [unoptimized + debuginfo] target(s) in 0.30s
Running `target/debug/variables`
The value of x is: 5
The value of x is: 6
通過 mut,允許把綁定到 x 的值從 5 改成 6。是否讓變量可變的最終決定權(quán)仍然在你,取決于在某個(gè)特定情況下,你是否認(rèn)為變量可變會(huì)讓代碼更加清晰明了。
正如在第二章猜數(shù)字游戲中所講,我們可以定義一個(gè)與之前變量同名的新變量。Rustacean 們稱之為第一個(gè)變量被第二個(gè) 隱藏(Shadowing) 了,這意味著當(dāng)您使用變量的名稱時(shí),編譯器將看到第二個(gè)變量。實(shí)際上,第二個(gè)變量“遮蔽”了第一個(gè)變量,此時(shí)任何使用該變量名的行為中都會(huì)視為是在使用第二個(gè)變量,直到第二個(gè)變量自己也被隱藏或第二個(gè)變量的作用域結(jié)束??梢杂孟嗤兞棵Q來(lái)隱藏一個(gè)變量,以及重復(fù)使用 let 關(guān)鍵字來(lái)多次隱藏,如下所示:
文件名: src/main.rs
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}");
}
這個(gè)程序首先將 x 綁定到值 5 上。接著通過 let x = 創(chuàng)建了一個(gè)新變量 x,獲取初始值并加 1,這樣 x 的值就變成 6 了。然后,在使用花括號(hào)創(chuàng)建的內(nèi)部作用域內(nèi),第三個(gè) let 語(yǔ)句也隱藏了 x 并創(chuàng)建了一個(gè)新的變量,將之前的值乘以 2,x 得到的值是 12。當(dāng)該作用域結(jié)束時(shí),內(nèi)部 shadowing 的作用域也結(jié)束了,x 又返回到 6。運(yùn)行這個(gè)程序,它會(huì)有如下輸出:
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
Finished dev [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/variables`
The value of x in the inner scope is: 12
The value of x is: 6
隱藏與將變量標(biāo)記為 mut 是有區(qū)別的。當(dāng)不小心嘗試對(duì)變量重新賦值時(shí),如果沒有使用 let 關(guān)鍵字,就會(huì)導(dǎo)致編譯時(shí)錯(cuò)誤。通過使用 let,我們可以用這個(gè)值進(jìn)行一些計(jì)算,不過計(jì)算完之后變量仍然是不可變的。
mut 與隱藏的另一個(gè)區(qū)別是,當(dāng)再次使用 let 時(shí),實(shí)際上創(chuàng)建了一個(gè)新變量,我們可以改變值的類型,并且復(fù)用這個(gè)名字。例如,假設(shè)程序請(qǐng)求用戶輸入空格字符來(lái)說(shuō)明希望在文本之間顯示多少個(gè)空格,接下來(lái)我們想將輸入存儲(chǔ)成數(shù)字(多少個(gè)空格):
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
error[E0308]: mismatched types
--> src/main.rs:3:14
|
2 | let mut spaces = " ";
| ----- expected due to this value
3 | spaces = spaces.len();
| ^^^^^^^^^^^^ expected `&str`, found `usize`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `variables` due to previous error
更多建議: