静态变量与常量
Static and constant variables are two different ways to create globally-scoped values that cannot be moved or reallocated during the execution of the program.
const
系统会在编译时对常量变量进行求值;无论在何处使用,其值都会被内嵌:
const DIGEST_SIZE: usize = 3; const ZERO: Option<u8> = Some(42); fn compute_digest(text: &str) -> [u8; DIGEST_SIZE] { let mut digest = [ZERO.unwrap_or(0); DIGEST_SIZE]; for (idx, &b) in text.as_bytes().iter().enumerate() { digest[idx % DIGEST_SIZE] = digest[idx % DIGEST_SIZE].wrapping_add(b); } digest } fn main() { let digest = compute_digest("Hello"); println!("digest: {digest:?}"); }
根据 Rust RFC Book 这些变量在使用时是内联 (inlined) 的。
在编译时只能调用标记为“const”的函数以生成“const”值。不过,可在运行时调用“const”函数。
static
静态变量在程序的整个执行过程中始终有效,因此不会移动:
static BANNER: &str = "Welcome to RustOS 3.14"; fn main() { println!("{BANNER}"); }
As noted in the Rust RFC Book, these are not inlined upon use and have an actual associated memory location. This is useful for unsafe and embedded code, and the variable lives through the entirety of the program execution. When a globally-scoped value does not have a reason to need object identity, const
is generally preferred.
- 值得一提的是,
const
在语义上与C++的constexpr
类似。 - 另一方面,
static
远远更类似于C++中的const
或可改变的全局变量。 static
provides object identity: an address in memory and state as required by types with interior mutability such asMutex<T>
.- 虽然需要使用在运行中求值的常量的情况并不是很常见,但是它是有帮助的,而且比使用静态变量更安全。
属性表:
属性 | Static | 常量 |
---|---|---|
在内存中有地址 | 是 | 否(内嵌) |
Lives for the entire duration of the program | 是 | 否 |
可变 | 是(不安全) | 否 |
Evaluated at compile time | 是(在编译时被初始化) | 是 |
内嵌在使用它的任何位置 | 否 | 是 |
探索更多
Because static
variables are accessible from any thread, they must be Sync
. Interior mutability is possible through a Mutex
, atomic or similar.
Thread-local data can be created with the macro std::thread_local
.