macro_rules! generic_static {
{static $ident:ident $(: &$type:ty)? = &$init:expr;} => { ... };
}Available on crate feature
alloc and (crate feature std or x86-64 or AArch64 or ARM or x86) only.Expand description
Declare a static variable that is not shared across different monomorphizations of the containing functions.
Its type must be a shared reference to a Sync+'static type,
and the initializer expression must start with a &.
Outer type variables may be used and the type hint is optional.
The initializing expression doesn’t need to be const.
If this is executed for the first time in multiple threads simultaneously,
the initializing expression may get executed multiple times.
§Example
fn numeric_type_id<T>() -> u32 {
static NEXT: AtomicU32 = AtomicU32::new(0);
generic_static!{
static ID: &u32 = &NEXT.fetch_add(1, Relaxed);
}
*ID
}
assert_eq!(numeric_type_id::<bool>(), 0);
assert_eq!(numeric_type_id::<String>(), 1);
assert_eq!(numeric_type_id::<i32>(), 2);
assert_eq!(numeric_type_id::<bool>(), 0);