常量

Rust 有两种不同类型的常量,可以在任何作用域(包括全局作用域)中声明。两者都需要显式的类型注解。

  • const: 一个不可变的值(常见情况)。
  • static: 一个可能可变的变量,具有 'static 生命周期。静态生命周期是推断出来的,不需要指定。访问或修改可变的静态变量是unsafe的。
// Globals are declared outside all other scopes.
static LANGUAGE: &str = "Rust";
const THRESHOLD: i32 = 10;

fn is_big(n: i32) -> bool {
    // Access constant in some function
    n > THRESHOLD
}

fn main() {
    let n = 16;

    // Access constant in the main thread
    println!("This is {}", LANGUAGE);
    println!("The threshold is {}", THRESHOLD);
    println!("{} is {}", n, if is_big(n) { "big" } else { "small" });

    // Error! Cannot modify a `const`.
    THRESHOLD = 5;
    // FIXME ^ Comment out this line
}

另请参阅

const/static RFC, 'static 生命周期