Rust 编程中的常量

rust programmingserver side programmingprogramming

Rust 为我们提供了两种类型的常量。它们是 −

  • const − 不可改变的值
  • static − 具有静态生命周期的可能可变值。

如果我们尝试将另一个值分配给已声明的 const 值,编译器将抛出错误。

示例

考虑下面显示的示例 −

static LANGUAGE: &str = "TutorialsPoint-Rust";
const THRESHOLD: i32 = 10;
fn is_small(n: i32) -> bool {
   n < THRESHOLD
}
fn main() {
   // 错误!无法修改 `const`。
   THRESHOLD = 5;
   println!("Everything working 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

相关文章