skip to content

In Rust, what is the difference between a `const` item and a `static` item, and when must you choose `static`?

level: middleimportance: should knowfreq 55%

answer

  1. value versus place
  2. inlined at every use
  3. one allocation, one address
  4. Sync bound on statics
  5. interior mutability needs a place

basics

~20 s

A const is a compile-time value copied into every place that uses it, with no fixed address. A static is one allocation for the whole program; choose it when you need a single address, interior mutability or a large table.

solid answer

~40 s

Both are items with an explicit type, an initializer evaluated at compile time, and the `'static` lifetime. A `const` is not tied to a memory location: the Reference says constants are "essentially inlined wherever they are used", so two references to one are not guaranteed to share an address, and each use of a `const` with a destructor is a fresh value dropped where it goes out of scope. A `static` is one allocation that every reference points to; it is never dropped, its type must be `Sync`, and an immutable one without interior mutability may sit in read-only memory. The Reference's guidance is to prefer `const` unless you store large data, need the single-address property, or need interior mutability, such as a `static ACCEPTED: AtomicU64` counter.

code

rust · 7 lines
rust
use std::cell::Cell;

static HITS: Cell<u32> = Cell::new(0);

fn main() {
    HITS.set(1);
}

go deeper

for a junior

Recall that both need a type annotation and a compile-time value, and that a const is copied into each use while a static is one object.

for a middle

Explain the Sync bound, why statics are never dropped, and the three reasons the Reference gives to pick static over const.

for a senior

Diagnose the E0015 and E0277 errors on statics and know when LazyLock is the answer instead of a const fn initializer.

for a principal

Keep shared mutable globals rare and visible: statics with atomics or locks only where a single object is the requirement, consts for every plain value.

## Two kinds of named compile-time item Rust has two ways to give a module-level name to a value computed at compile time. Both are **items**, so they can sit at the top of a file or inside a function; both need an explicit type (`const LIMIT: u32 = 100;`); both have initializers that the compiler evaluates during compilation; and both have the `'static` lifetime. The naming convention for both is upper snake case. The difference is what the name stands for: a `const` names a **value**, a `static` names a **place** in memory. ## `const`: a value pasted at every use The Reference describes a constant item as "not associated with a specific memory location in the program" and says constants are "essentially inlined wherever they are used". Consequences: - **No fixed address.** "References to the same constant are not necessarily guaranteed to refer to the same memory address." The compiler may still share one copy when it promotes the value, so identity is neither promised nor forbidden; it is unspecified. - **Each use is a new value.** A `const` of a type with `Drop` creates a value at each use, and that value is dropped where it goes out of scope. - **Always evaluated.** A free `const` is evaluated at compile time even if nothing uses it, so `const _: () = assert!(usize::BITS == 64);` is a compile-time check. - **Usable in type positions.** A `const` can size an array, `[u16; MAX_PORTS]`, and feed const generics. Initializers may call only `const fn` functions. Writing `const fn kib(n: usize) -> usize { n * 1024 }` lets `const READ_BUFFER: usize = kib(8);` compute at compile time. An inline `const { ... }` block does the same inside an expression without naming an item. ## `static`: one allocation for the program A static "represents an allocation in the program", and "all references and raw pointers to the static refer to the same allocation". Further rules from the Reference: - It lives for the whole program and **is never dropped**: "Static items do not call drop at the end of the program." - Its type **must be `Sync`**, because any thread may read it. `Cell<u32>` is not `Sync`, so a `static` of it fails with E0277. - An immutable static whose type has no interior mutability **may be placed in read-only memory**. - It cannot be assigned: `NAME = 1;` on a plain `static` fails with E0594, "cannot assign to immutable static item". Mutation goes through interior mutability, such as an atomic or a `Mutex`. (The `static mut` form and its unsafety belong with unsafe Rust.) ```rust use std::sync::atomic::{AtomicU64, Ordering}; const MAX_CONNECTIONS: usize = 512; // a value, inlined at each use const fn kib(n: usize) -> usize { n * 1024 } const READ_BUFFER: usize = kib(8); // const fn runs at compile time static ACCEPTED: AtomicU64 = AtomicU64::new(0); // one shared allocation fn accept() -> u64 { ACCEPTED.fetch_add(1, Ordering::Relaxed) + 1 } fn main() { let buf = vec![0u8; READ_BUFFER]; for _ in 0..3 { accept(); } println!("{} {} {}", MAX_CONNECTIONS, buf.len(), ACCEPTED.load(Ordering::Relaxed)); } ``` It prints `512 8192 3`: the constants are plain numbers baked into the code, and all three calls to `accept` incremented the same atomic. ## Side by side | | `const` | `static` | |---|---|---| | Names | a value | a memory location | | Address | not guaranteed stable | one address for every reference | | Each use | a fresh copy | the same object | | Drop | each copy dropped at its scope's end | never dropped | | Type bound | none beyond `'static` | must be `Sync` | | Interior mutability | each use mutates a temporary | shared by all users | | Initializer | compile-time constant expression | compile-time constant expression | ## Choosing between them The Reference's own rule is to prefer `const` "unless one of the following are true": 1. Large amounts of data are being stored, such as a lookup table you do not want duplicated at every use. 2. The single-address property is required, for example when code compares addresses or hands out a pointer to the item. 3. Interior mutability is required: counters, flags and locks. Two errors show up when the choice goes wrong. A run-time initializer, such as `static GREETING: String = String::from("hello");`, fails with E0015, "cannot call non-const associated function", and rustc suggests `std::sync::LazyLock::new(|| ...)`. A non-`Sync` type behind a `static` fails with E0277: ```plaintext error[E0277]: `Cell<u32>` cannot be shared between threads safely --> e11.rs:3:14 | 3 | static HITS: Cell<u32> = Cell::new(0); | ^^^^^^^^^ `Cell<u32>` cannot be shared between threads safely | = help: the trait `Sync` is not implemented for `Cell<u32>` = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` or `std::sync::atomic::AtomicU32` instead = note: shared static variables must have a type that implements `Sync` ``` In short: reach for `const` for numbers, strings and small tables; reach for `static` when the program needs one shared object.

  • In Rust, how do you get a global whose value needs run-time work, such as a `String` built from configuration?
    A `static` initializer must be a compile-time constant, so `String::from` there fails with E0015, and rustc suggests wrapping it in `std::sync::LazyLock::new(|| ...)`. A `static CONFIG: LazyLock<String>` runs its closure on first access and then hands every caller the same value. The once-cell and lazy-initialisation material covers those types in depth.
  • In Rust, may code rely on two `&LIMIT` references to a `const LIMIT` having the same address?
    No. The Reference says references to the same constant are not necessarily guaranteed to refer to the same memory address. On rustc 1.99.1 `std::ptr::eq` on two `&CTABLE` references to a small const array returned `true`, because the value was promoted, but that is an unspecified detail. When identity matters, use a `static`.

  • A `const` is a read-only global variable stored at one fixed address.
  • A `static` may hold any type, whether or not it is `Sync`.
  • Statics are dropped in order when the program exits.
  • A `const` initializer runs once at program start-up.
  • A `const` and a `static` can both be reassigned with plain `=` in safe code.