Generate unique IDs in const context
⚓ Rust 📅 2025-10-08 👤 surdeus 👁️ 3I'm generating unique IDs in my project by incrementing an atomic integer. This works fine at runtime but I would like to generate some global static unique IDs too, which is a problem because fetch_add is not a const function (presumably because it mutates the atomic):
static COUNTER: AtomicU64 = AtomicU64::new(0);
fn new_id() -> u64 {
COUNTER.fetch_add(1, Ordering::Relaxed)
}
// This doesn't work because new_id() is not const
static MY_ID: u64 = new_id();
Is there any way to make this work, other than lazy initialization?
(I don't need the IDs to be predicatable nor unique between runs, they only need to be unique for the duration of my program's runtime.)
13 posts - 5 participants
🏷️ Rust_feed