static & const

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.


Constant variables are evaluated at compile time and their values are inlined wherever they are used:

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);

fn main() {
    let digest = compute_digest("Hello");
    println!("digest: {digest:?}");

GemĂ€ĂŸ dem Rust RFC Book werden diese bei der Verwendung eingefĂŒgt (inlined upon use).

Only functions marked const can be called at compile time to generate const values. const functions can however be called at runtime.


Static variables will live during the whole execution of the program, and therefore will not move:

static BANNER: &str = "Welcome to RustOS 3.14";

fn main() {

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.

This slide should take about 5 minutes.
  • ErwĂ€hne, dass sich const semantisch Ă€hnlich wie constexpr in C++ verhĂ€lt.
  • static hingegen ist einer const oder verĂ€nderlichen (mutable) globalen Variable in C++ viel Ă€hnlicher.
  • static provides object identity: an address in memory and state as required by types with interior mutability such as Mutex<T>.
  • Es kommt nicht sehr hĂ€ufig vor, dass man eine zur Laufzeit ausgewertete Konstante benötigt, aber es ist hilfreich und sicherer als die Verwendung einer statischen.

Properties table:

Has an address in memoryYesNo (inlined)
Lives for the entire duration of the programYesNo
Can be mutableYes (unsafe)No
Evaluated at compile timeYes (initialised at compile time)Yes
Inlined wherever it is usedNoYes

More to Explore

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.