Constants in Rust
Use const and static for compile‑time and global values. Both require explicit types.
const (inline constants)
Evaluated at compile time; usable in any scope and in const contexts.
const PI: f64 = 3.14159;
const MAX_RETRIES: u32 = 3;
fn area(r: f64) -> f64 { PI * r * r }
static (single address)
Has a fixed memory address for the program’s lifetime.
static APP_NAME: &str = "GistDev";
static mut (unsafe)
Mutable global state is unsafe and requires unsafe to read/write; avoid where possible.
static mut COUNTER: u32 = 0;
unsafe { COUNTER += 1; }
Prefer interior mutability (Mutex, Atomic*, or OnceLock) for safe shared state.
use std::sync::OnceLock;
static CONFIG: OnceLock<String> = OnceLock::new();
const fn
Define functions evaluable at compile time to produce consts.
const fn square(n: i32) -> i32 { n * n }
const NINE: i32 = square(3);
Types and literals
Constants require types; numeric literals can use suffixes (42u64) or context for inference.
Naming
Use SCREAMING_SNAKE_CASE for const and static.
Summary
const= compile‑time values;static= one address for program lifetime- Avoid
static mut; use safe abstractions for global mutable state - Use
const fnto compute constants at compile time