capypad
0 day streak
rust / beginner
Snippet

Constants vs Static Variables

Constants are inlined at compile time and can be used anywhere. Static variables are stored in memory at a fixed address and live for the entire program duration. Static mut requires unsafe blocks for access due to Rust's safety guarantees against data races.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
const GRAVITY: f64 = 9.81;
static mut COUNTER: u32 = 0;
 
fn main() {
println!("Gravity: {}", GRAVITY);
unsafe {
COUNTER += 1;
println!("Counter: {}", COUNTER);
}
}
Breakdown
1
const GRAVITY: f64 = 9.81;
Compile-time constant, inlined everywhere it's used
2
static mut COUNTER: u32 = 0;
Mutable static variable with fixed memory address
3
unsafe {
Required block for accessing static mut
4
COUNTER += 1;
Direct mutation of static variable