Rust 程式語言常量
Rust 為我們提供了兩種型別的常量。這些是 -
- const - 不可更改的值
- static - 具有靜態生命週期的可能可變的值。
如果我們嘗試為已宣告的 const 值分配另一個值,編譯器將丟擲錯誤。
示例
考慮以下所示的示例 -
static LANGUAGE: &str = "TutorialsPoint-Rust";
const THRESHOLD: i32 = 10;
fn is_small(n: i32) -> bool {
n < THRESHOLD
}
fn main() {
// Error! Cannot modify a `const`.
THRESHOLD = 5;
println!("Everything worked fine!");
}在上面的程式碼中,我們試圖修改一個已經宣告為 const 關鍵字的變數的值,這是不允許的。
輸出
error[E0070]: invalid left-hand side of assignment --> src/main.rs:12:15 | 12| THRESHOLD = 5; | --------- ^ | | | cannot assign to this expression
我們還可以訪問在其他函式中宣告的常量。
示例
考慮以下所示的示例 -
static LANGUAGE: &str = "TutorialsPoint-Rust";
const THRESHOLD: i32 = 11;
fn is_small(n: i32) -> bool {
n < THRESHOLD
}
fn main() {
let n = 19;
println!("This is {}", LANGUAGE);
println!("The threshold is {}", THRESHOLD);
println!("{} is {}", n, if is_small(n) { "small" } else { "big" });
}輸出
This is TutorialsPoint-Rust The threshold is 11 19 is big
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP