3.1 變量和可變性

一 創(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)鍵字用法

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容