一 創(chuàng)建項(xiàng)目
cargo new variables
二 變量可變性的實(shí)例錯(cuò)誤代碼
vim ./src/main.rs
fn main() {
let x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
}
三 編譯查看錯(cuò)誤提示
cargo run
cargo run
Compiling variables v0.1.0 (/home/li/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: make this binding mutable: `mut x`
3 | println!("The value of x is: {}", x);
4 | x = 6;
| ^^^^^ cannot assign twice to immutable variable
error: aborting due to previous error
小結(jié):默認(rèn)情況,let定義的變量是不可變的,如果可變需加關(guān)鍵字mut
四 增加mut關(guān)鍵字,讓變量可變
vim ./src/main.rs
fn main() {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
}
輸出
cargo run
Compiling variables v0.1.0 (/home/li/projects/variables)
Finished dev [unoptimized + debuginfo] target(s) in 4.98s
Running `target/debug/variables`
The value of x is: 5
The value of x is: 6
五 常量
使用const關(guān)鍵字定義常量
const MAX_POINTS: u32 = 100_000; //在數(shù)字字面值下面插入下劃線來提高數(shù)字可讀性,這里等價(jià)于 100000
六 隱藏(shadowing)變量
重復(fù)使用let關(guān)鍵字,定義同名變量來隱藏之前的變量。
實(shí)際上是創(chuàng)建一個(gè)新的變量。
可改變變量的類型和值
fn main() {
let x = 5;
println!("The value of x is: {}", x);
let x = "6+1";
println!("The value of x is: {}", x);
}
如果使用mut,則會(huì)報(bào)編譯錯(cuò)誤
因?yàn)閙ut不允許改變變量類型
fn main() {
let mut x = 5;
println!("The value of x is: {}", x);
x = "6+1";
println!("The value of x is: {}", x);
}
cargo run
Compiling variables v0.1.0 (/home/li/projects/variables)
error[E0308]: mismatched types
--> src/main.rs:4:9
|
4 | x = "6+1";
| ^^^^^ expected integer, found reference
|
= note: expected type `{integer}`
found type `&'static str`
七總結(jié)
1 使用大型數(shù)據(jù)結(jié)構(gòu)時(shí),適當(dāng)?shù)厥褂每勺冏兞?br>
2 對(duì)于較小的數(shù)據(jù)結(jié)構(gòu),總是創(chuàng)建新實(shí)例
3 了解let,mut,const關(guān)鍵字用法