The safety invariants of unsafe require you to manually guarantee that raw pointers are valid, mutable statics are accessed by only one thread, and no undefined behavior occurs. You must uphold these guarantees yourself because the compiler skips its usual safety checks inside unsafe blocks.
static mut COUNTER: u32 = 0;
/// SAFETY: Calling this from more than a single thread at a time is undefined
/// behavior, so you *must* guarantee you only call it from a single thread at
/// a time.
unsafe fn add_to_count(inc: u32) {
unsafe {
COUNTER += inc;
}
}
fn main() {
unsafe {
// SAFETY: This is only called from a single thread in `main`.
add_to_count(3);
println!("COUNTER: {}", *(&raw const COUNTER));
}
}