Sub topic 5
const and static items
This chapter assumes you know let bindings, mut, and shadowing from the earlier chapters. It also assumes you can read basic Rust type annotations such as u32 and &str.
Why a second kind of named value
A let binding lives inside a function or block and is created when execution reaches it. Some values belong to the whole program instead: a conversion factor, a default port, a greeting. Rust has two item kinds for these, const and static. Both are declared at module level or inside a function, and both are available for the whole scope they are declared in.
const SECONDS_PER_HOUR: u32 = 60 * 60;
static GREETING: &str = "hello";
fn main() {
println!("{SECONDS_PER_HOUR} {GREETING}");
}This prints 3600 hello.
const: a named compile-time value
A const is a name for a value the compiler computes during compilation. Three rules apply:
- The type annotation is required. Inference is not used for items.
- The initializer must be a constant expression. Arithmetic, other constants, array and tuple literals, and calls to
const fnfunctions are allowed. A call to an ordinary function is not. - By convention the name is
SCREAMING_SNAKE_CASE.
const MAX_RETRIES: u32 = 3;
const TIMEOUT_SECONDS: u32 = 30 * MAX_RETRIES;
const PRIMES: [u32; 3] = [2, 3, 5];
fn main() {
println!("{MAX_RETRIES} {TIMEOUT_SECONDS} {}", PRIMES.len());
}A const has no fixed address. The compiler inlines it, so every use behaves like a fresh copy of the value. Taking &PRIMES twice may give two different addresses. Do not rely on a const having one identity in memory.
A const is never mut. Unlike let, it cannot be declared first and assigned later. It is immutable everywhere, and const mut is a syntax error.
static: one value at one address
A static is a single item stored in a fixed memory location for the entire run of the program. Every reference to it points to the same address.
static APP_NAME: &str = "demo";
fn main() {
let a: &'static str = APP_NAME;
println!("{a}");
}Like const, it needs a type annotation and a constant initializer. Use static when the address matters, for example when you hand out references that must live as long as the program, or when you hold a large value you don't want copied at each use.
Mutable statics
A plain static is read-only. A global that changes needs a type that is safe to modify from many threads. Atomic types are the usual choice for counters, because their methods take &self:
use std::sync::atomic::{AtomicUsize, Ordering};
static REQUESTS: AtomicUsize = AtomicUsize::new(0);
fn main() {
REQUESTS.fetch_add(1, Ordering::Relaxed);
REQUESTS.fetch_add(1, Ordering::Relaxed);
println!("{}", REQUESTS.load(Ordering::Relaxed));
}This prints 2. The static itself is immutable, and the mutation happens inside the atomic type. This is the interior mutability idea from the end of this tutorial.
Choosing between let, const, and static
| Feature | `let` | `const` | `static` |
|---|---|---|---|
| Type annotation | Optional | Required | Required |
| Value known at compile time | No | Yes | Yes |
| Fixed memory address | No | No (inlined) | Yes |
| Can be `mut` | Yes | No | Only as `static mut`, with `unsafe` |
| Lives for | Its block | Not applicable, inlined | Whole program |
Default to const for fixed numbers and strings. Use static only when you need the single address or a global with interior mutability. Use let for anything computed while the program runs.
Common errors
- Missing type:
const LIMIT = 10;fails with "missing type forconstitem". Writeconst LIMIT: u32 = 10;. - Non-constant initializer:
const NAME: String = String::from("x");fails becauseString::fromis not aconst fn. Use&str, or build theStringat run time. - Assigning to a static:
GREETING = "bye";fails because a plainstaticis immutable.
Exercise
You write const START: u32 = compute(); where compute is an ordinary function that returns 42. The compiler rejects it. Give two ways to fix this, and say which keyword you would pick if START had to be computed from a command-line argument.
Show answer
First, declare compute as const fn so it can run at compile time. Second, replace the call with the literal 42. A value taken from a command-line argument is only known at run time, so neither const nor static works. Use let START: u32 = ...; inside main.