Example code:
use std::sync::atomic::{AtomicU32, Ordering};
#[derive(Debug)]
struct Token(u32);
impl Token {
fn new() -> Self {
static COUNTER: AtomicU32 = AtomicU32::new(1);
let inner = COUNTER.fetch_add(1, Ordering::Relaxed);
Token(inner)
}
}
fn main() {
let t1 = Token::new();
let t2 = Token::new();
let t3 = Token::new();
println!("{:?}\n{:?}\n{:?}", t1, t2, t3);
}
When I run the code snippet shown above, it prints:
Token(1)
Token(2)
Token(3)
I found in Rust reference that static items' initialization are evaluated at compile time.
I wonder what exactly happens at runtime when the program executes up to the line that initializes the variable COUNTER. What the compiled code looks like so that it could neglect the initialization?