一 創(chuàng)建項目
cargo new variables
二 變量可變性的實例錯誤代碼
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);
}
三 編譯查看錯誤提示
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é):默認情況谦秧,let定義的變量是不可變的,如果可變需加關鍵字mut
四 增加mut關鍵字馋评,讓變量可變
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關鍵字定義常量
const MAX_POINTS: u32 = 100_000; //在數(shù)字字面值下面插入下劃線來提高數(shù)字可讀性,這里等價于 100000
六 隱藏(shadowing)變量
重復使用let關鍵字,定義同名變量來隱藏之前的變量嗡综。
實際上是創(chuàng)建一個新的變量簇捍。
可改變變量的類型和值
fn main() {
let x = 5;
println!("The value of x is: {}", x);
let x = "6+1";
println!("The value of x is: {}", x);
}
如果使用mut只壳,則會報編譯錯誤
因為mut不允許改變變量類型
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é)構時,適當?shù)厥褂每勺冏兞?br>
2 對于較小的數(shù)據(jù)結(jié)構暑塑,總是創(chuàng)建新實例
3 了解let吼句,mut,const關鍵字用法