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