Rust常量
Rust有两种不同类型,可以在任何范围内,包括全局声明的常量。这都需要显式类型注解声明:
-
const
: 一个不可改变值(通常情况下)。 -
static
:%uA0有一个可能是可变的变量%uA0&aposstatic
%uA0使用寿命。
一个特殊情况是%uA0"string"
%uA0常量. 它可以直接被分配到一个%uA0static
%uA0变量不需要修改,因为它的类型签名:%uA0&&aposstatic str
%uA0具有所要求的使用寿命为%uA0&aposstatic
. 所有其他类型的引用必须特别注明,以便它们完成%uA0&aposstatic
%uA0使用寿命. 这看似微小,但因为需要明确标注隐藏以区别。
// Globals are declared outside all other scopes. static LANGUAGE: &&aposstatic 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 }
另请参见:
%uA0const
/static
%uA0RFC,%uA0&aposstatic
%uA0使用寿命