Sub topic 5
const and static items
This chapter covers Rust's two kinds of global value: const and static. It assumes you know let bindings, mut, and basic types such as u32 and &str. It also assumes you can read a compiler error. Neither item is a variable in the let sense. Each is declared at the top level of a module (or inside a function body), and each needs an explicit type. Choosing between them depends on whether the value needs a memory address.
What a const is
A const names a value computed at compile time. The compiler substitutes the value at each place you use the name, as if you had typed the value there. A const has no identity of its own.
const SECONDS_PER_HOUR: u32 = 60 * 60;
static GREETING: &str = "hello";
fn main() {
println!("{SECONDS_PER_HOUR} {GREETING}");
}This program prints 3600 hello. These rules apply to every const:
- The type is required.
const N = 5;does not compile, because items never use type inference. - The initializer must be a constant expression. The compiler evaluates it during compilation.
- A
constis nevermut. Writingconst mutis a syntax error. - By convention the name is
SCREAMING_SNAKE_CASE. The compiler warns if you use another style. - You can declare a
constin any scope: module level, inside a function, or inside animplblock (an associated constant).
Constant expressions allow literals, arithmetic, comparisons, other constants, tuple, array, and struct construction, if and match, and calls to const fn functions. They do not allow heap allocation or ordinary function calls.
const fn
A function marked const fn can run at compile time as well as at run time. The result can then initialize a const.
const fn square(n: u32) -> u32 {
n * n
}
const AREA: u32 = square(12);
const MAX_USERS: usize = 4;
static SLOTS: [u8; MAX_USERS] = [0; MAX_USERS];
fn main() {
println!("{AREA} {}", SLOTS.len());
}The program prints 144 4. Array lengths must be known at compile time, so MAX_USERS can serve as a length. A plain let n = 4; cannot.
Many standard library functions are const fn. Examples are String::new(), Vec::new(), and u32::pow. String::from("x") is not, so it cannot appear in a const initializer.
Consts in patterns
A const can be a pattern in match. A static cannot, because it is a place in memory and not a value known at compile time.
const MAX: u32 = 100;
fn classify(n: u32) -> &'static str {
match n {
0 => "zero",
MAX => "max",
_ => "other",
}
}
fn main() {
println!("{} {} {}", classify(0), classify(100), classify(7));
}This prints zero max other. If you misspell a constant in a pattern, the compiler reads the misspelling as a new binding that matches anything. Keep the unreachable pattern and unused variable warnings visible so you notice this.
What a static is
A static is a single value stored at a fixed memory address for the whole run of the program. Every use of the name refers to that one location.
static VERSION: &str = "1.4.2";
static LIMITS: [u32; 3] = [10, 20, 30];
fn main() {
let first = &LIMITS as *const [u32; 3];
let second = &LIMITS as *const [u32; 3];
println!("{VERSION} {}", first == second);
}The program prints 1.4.2 true. Both pointers refer to the same location, because there is one LIMITS. You cannot rely on this for a const. The compiler may create a fresh copy at each use, so two references to the same const may or may not have the same address.
Rules for static:
- It needs an explicit type, just like
const. - Its initializer must be a constant expression, evaluated at compile time. The program never runs initialization code for a
staticat startup. - A non-
mutstatic must have a type that implementsSync.Syncmeans the type is safe to share between threads. Any thread may read a static, so the compiler requires this. - The value is never dropped, because the program does not run destructors for statics at exit.
Both items use the 'static lifetime
References in a const or static type get the 'static lifetime by default. &str in static GREETING: &str means &'static str. You do not need to write the lifetime.
const versus static
| Question | `const` | `static` |
|---|---|---|
| Has a memory address | No guaranteed address. The value is inlined. | Yes, one fixed address. |
| Can be `mut` | No | Yes, as `static mut`, but only with `unsafe` |
| Allowed in `match` patterns | Yes | No |
| Can be used as an array length | Yes, if it is an integer | No |
| Interior mutability | Each use gets a fresh copy, so changes are lost | Changes persist and are shared |
| Type must be `Sync` | No | Yes (for non-`mut` statics) |
| Typical use | Named numbers, sizes, flags, lookup values | Shared tables, global state, FFI symbols |
A good default is const. Use static when you need one shared object with an address. Examples are a large lookup table you do not want copied into every use, a value that foreign code must find by address, or a global with interior mutability.
Interior mutability: where const and static diverge
Because a const is copied to each use, a type with interior mutability behaves surprisingly inside one. Interior mutability means a type can change through a shared reference. Cell is an example. The atomic integer types are another.
use std::sync::atomic::{AtomicUsize, Ordering};
const COUNTER: AtomicUsize = AtomicUsize::new(0);
fn main() {
COUNTER.fetch_add(1, Ordering::SeqCst);
COUNTER.fetch_add(1, Ordering::SeqCst);
println!("{}", COUNTER.load(Ordering::SeqCst));
}This prints 0, not 2. Each mention of COUNTER creates a new atomic starting at zero, increments it, and throws it away. The code compiles without error. The Clippy lint declare_interior_mutable_const flags this pattern. Change const to static and the program prints 2:
use std::sync::atomic::{AtomicUsize, Ordering};
static REQUESTS: AtomicUsize = AtomicUsize::new(0);
fn handle() -> usize {
REQUESTS.fetch_add(1, Ordering::Relaxed) + 1
}
fn main() {
handle();
handle();
println!("{}", REQUESTS.load(Ordering::Relaxed));
}The output is 2. The static is shared and changes through &REQUESTS, so no mut and no unsafe are needed. This is the standard way to keep a global counter. For data that is more than a single integer, wrap it in a Mutex or RwLock. Since Rust 1.63, Mutex::new is a const fn, so static NAMES: Mutex<Vec<String>> = Mutex::new(Vec::new()); is valid.
A non-thread-safe type such as Cell fails in a static. static C: Cell<i32> = Cell::new(0); produces error E0277 saying that Cell<i32> cannot be shared between threads safely. That message is Sync enforcing its rule.
static mut and why to avoid it
A static mut can be assigned directly, but every access needs an unsafe block.
static mut COUNTER: u32 = 0;
fn main() {
unsafe {
COUNTER += 1;
}
let value = unsafe { COUNTER };
println!("{value}");
}This prints 1. The unsafe keyword means you promise the compiler that no two threads touch the value at once and that no reference to it is alive during a write. The compiler cannot check either promise. A data race on a static mut is undefined behavior.
In the 2024 edition, creating a reference to a static mut is a hard error. That includes println!("{}", COUNTER), which borrows the value. Earlier editions warn by default. Copying the value out, as in the example, avoids the reference.
Values that cannot be computed at compile time
A static initializer must be a constant expression, so this fails:
// error: cannot call non-const associated function `String::from` in statics
// static NAME: String = String::from("rust");
static NAME: String = String::new();
fn main() {
println!("[{NAME}]");
}The program prints []. When you need a value that depends on run-time work, such as building a HashMap, use a lazy wrapper from the standard library. LazyLock runs its closure on first access and then keeps the result. OnceLock is similar, but you fill it explicitly with set or get_or_init.
use std::collections::HashMap;
use std::sync::LazyLock;
static PORTS: LazyLock<HashMap<&'static str, u16>> = LazyLock::new(|| {
HashMap::from([("http", 80), ("https", 443)])
});
fn main() {
println!("{:?}", PORTS.get("https"));
}This prints Some(443). LazyLock has been stable since Rust 1.80. Older code uses the lazy_static or once_cell crates for the same purpose.
Common mistakes
- Omitting the type.
const LIMIT = 10;gives "missing type forconstitem". Writeconst LIMIT: u32 = 10;. - Calling a non-const function in an initializer. The error says the function is not
const. Use aconst fn, a literal, orLazyLock. - Using a const as a counter. The code compiles, but updates vanish because each use is a fresh copy. Use a
staticwith an atomic. - Reaching for
static mutfirst. It compiles only withunsafe, and a data race is undefined behavior. Use an atomic or aMutex. - Using a
letvalue where a constant is needed. An array length or aconstinitializer cannot depend on aletvariable, even an immutable one. Declare it as aconst. - Expecting shadowing to work. A
letbinding can shadow anotherlet. Aconstis an item and is not rebound that way, so choose a different name.
Summary of when to choose each
Use let for values computed at run time. Use const for fixed values the compiler can inline, including array sizes and match patterns. Use static when the value needs one address or must hold shared state. Pair the shared state with an atomic, Mutex, or LazyLock.
Exercise
A programmer writes const HITS: AtomicUsize = AtomicUsize::new(0);, calls HITS.fetch_add(1, Ordering::SeqCst) in three different functions, then prints HITS.load(Ordering::SeqCst). It prints 0. Why, and what is the smallest change that makes it print 3?
Show answer
A const is inlined, so each mention of HITS creates a separate new AtomicUsize that starts at 0. The three increments each affect a temporary copy that is then discarded, and the final load reads yet another fresh copy. Changing const to static gives one shared value at a fixed address, so all three increments accumulate and the program prints 3.
Exercise
Which of these compile? (a) const N: usize = 3; let a = [0u8; N]; (b) static N: usize = 3; match x { N => {}, _ => {} } (c) static S: String = String::from("hi"); (d) static mut T: u32 = 0; unsafe { T += 1; } Give a reason for each.
Show answer
(a) compiles, because a const integer is a valid array length. (b) does not compile, because a static cannot be used as a pattern, only a const can. (c) does not compile, because String::from is not a const fn and a static initializer must be a constant expression. (d) compiles, because assigning to a static mut is allowed inside unsafe.