在預設情況下rust變數是不可變的。這樣可以使**更加安全。讓我們**一下rust如何以及為什麼鼓勵您支援變數不可變,以及為什麼有時您可以選擇可變變數。
通過let關鍵字宣告變數,可以不宣告變數型別,交由編譯器判斷。
let spaces = "";
也可以宣告變數型別:
let spaces:&str = "";
以下**為錯誤**:
fn main() ", x);
x = 6;
println!("the value of x is: {}", x);
}
以下為錯誤資訊:
$ 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: 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
for more information about this error, try `rustc --explain e0384`.
error: could not compile `variables`.
to learn more, run the command again with --verbose.
錯誤訊息表明錯誤的原因是cannot assign twice to immutable variable x,因為您試圖為不可變變數x分配第二個值。嘗試更改以前指定為不可變的變數時,將會丟擲編譯時錯誤。
如此設計的原因:
如果我們的**的一部分在假設值永遠不會改變的情況下執行,而我們**的另一部分則在改變該值,那麼**的第一部分可能不會按照設計的意圖進行操作。實際上,這類錯誤的原因可能很難追查,尤其是在第二段**有時僅更改值時。
在很多時候可變變數是必要的。我們可以通過新增mut關鍵字使變數可變。
fn main() ", x);
x = 6;
println!("the value of x is: {}", x);
}
常量與不可變變數有些相似,但是有區別。
不允許使用mut常量。常量在預設情況下不僅是不可變的,還總是不可變的。
宣告常量使用const關鍵字,並且必須宣告常量型別。
const max_points: u32 = 100_000;
常量可以在任何範圍內宣告,包括全域性範圍,這使它們對於許多**部分需要知道的值很有用。
常量只能設定為常量表示式,而不能設定為函式呼叫的結果或只能在執行時計算的任何其他值。
您可以宣告乙個與先前變數同名的新變數,並且該新變數會覆蓋先前的變數。使用let關鍵字。
fn main() ", x);
}
結果是12。
遮蔽(shadowing)不同於將變數標記為mut,遮蔽(shadowing)後的變數依舊是不可變的。
遮蔽(shadowing)可以使變數型別改變。因為當我們let再次使用關鍵字時,我們正在有效地建立乙個新變數,因此我們可以更改值的型別,重複使用相同的名稱。
可以看到原先變數為&str,後變為usize型別。
使用mut則不能改變變數型別,以下為錯誤**:
fn main()
$ cargo run
compiling variables v0.1.0 (file:///projects/variables)
error[e0308]: mismatched types
--> src/main.rs:3:14
|3 | spaces = spaces.len();
| ^^^^^^^^^^^^ expected `&str`, found `usize`
error: aborting due to previous error
for more information about this error, try `rustc --explain e0308`.
error: could not compile `variables`.
to learn more, run the command again with --verbose.
Rust 入門 變數與可變性
fn main x x 6 如果我們對乙個不可變得變數進行再次賦值的操作 編譯器會丟擲乙個異常 cannot assign twice to tmmutable variable println x x fn main x x 6 println x x cargo run x 5 x 6 在程式執...
Rust常用程式設計概念之變數和可變性
time 20190921 rust的學習曲線相對陡峭,更好的學習方式是先把概念理清楚,形成相對巨集觀的認知後,再動手實踐,和一般的語言學習方式略有不同。具體說就是,會涉及到rust語言的以下概念 預設情況下,變數是不可變的,如果想讓變數顯式可變,則用mut關鍵字修飾即可。那我們一定想問,這麼設計的...
Rust中的RefCell和內部可變性
refcell rust在編譯階段會進行嚴格的借用規則檢查,規則如下 即在編譯階段,當有乙個不可變值時,不能可變的借用它。如下 所示 fn main 會產生編譯錯誤 error e0596 cannot borrow immutable local variable x as mutable src...