capypad
0 day streak
rust / beginner
Snippet

Constants and Static Variables

Constants (const) are immutable at compile time with no fixed memory address. Static variables (static) have a fixed memory address and live for the program's entire lifetime. Accessing mutable statics requires unsafe blocks because of data races.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
const MAX_SCORE: i32 = 100;
static GAME_NAME: &str = "RustQuiz";
static mut COUNTER: u32 = 0;
 
fn main() {
println!("Max score: {}", MAX_SCORE);
println!("Game: {}", GAME_NAME);
unsafe {
COUNTER += 1;
println!("Counter: {}", COUNTER);
}
}
Breakdown
1
const MAX_SCORE: i32 = 100;
Compile-time constant, inlined everywhere it's used
2
static GAME_NAME: &str
Static has fixed memory address for program lifetime
3
static mut COUNTER: u32 = 0;
Mutable static requires unsafe to access
4
unsafe { ... }
Unsafe block needed to modify mutable static