Static variables
- Rust course
- Beginner
- Lesson 10/115
- 4 min
Define static-lifetime variables with static.
static variables
A static is a value that lives at a fixed memory address for the whole lifetime of the program. While a const is copied at every use, a static is a single instance:
static UYGULAMA: &str = "Not Defteri";
fn main() {
println!("{}", UYGULAMA);
}Its type has a 'static lifetime. String literals ("...") are actually of type &'static str too.
Safe global state
For a global counter that must change, atomic types are used; no unsafe is needed:
use std::sync::atomic::{AtomicU32, Ordering};
static ISTEK: AtomicU32 = AtomicU32::new(0);
fn kaydet() {
ISTEK.fetch_add(1, Ordering::Relaxed);
}For global values computed once at run time there is std::sync::OnceLock.
Practice Atomic counter
Define static SAYAC: AtomicU32 = AtomicU32::new(0);. In main, call SAYAC.fetch_add(1, Ordering::Relaxed); three times and print SAYAC.load(Ordering::Relaxed).
Starter code
use std::sync::atomic::{AtomicU32, Ordering};
fn main() {
// buraya yaz
}Sample solution
use std::sync::atomic::{AtomicU32, Ordering};
static SAYAC: AtomicU32 = AtomicU32::new(0);
fn main() {
for _ in 0..3 {
SAYAC.fetch_add(1, Ordering::Relaxed);
}
println!("{}", SAYAC.load(Ordering::Relaxed));
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why does accessing a <code>static mut</code> require <code>unsafe</code>?
- static is always unsafe
- It doesn't
- If several threads write at once there can be a data race Correct answer
- Because it's slower
Explanation: The compiler can't check concurrent access to global mutable state; safe alternatives are AtomicUsize, Mutex or OnceLock.
2 Global value
____ SURUM: &str = "1.2.0";
static SURUM: &str = "1.2.0";
Explanation: static defines a global value that lives for the program's lifetime.
3 Definition and property
| Term | Meaning |
|---|---|
const |
Copied at each use |
static |
A single memory address |
static mut |
Requires unsafe |
AtomicU32 |
Safe global counter |