⚠ Nightly ⚠
Quoting the Rust Reference:
"A static item defined in a generic scope (for example in a blanket or default implementation) will result in exactly one static item being defined, as if the static definition was pulled out of the current scope into the module. There will not be one item per monomorphization."
One way to work around this is to use a HashMap<TypeId,Data>
. This is a simple & usually appropriate solution.
If lookup performance is important, you can skip hashing the TypeId
for minor gains as it
already contains
a good-quality hash. This is implemented in TypeIdMap
.
This crate aims to further fully remove the lookup by allocating the storage using inline assembly.
Supported targets are x86-64 and aarch64. On other targets, the generic_static
macro
falls back to a hashmap and most other functionality is unavailable.
Additionally, different compilation units may access different instances of the data!
This crate requires the following unstable features: asm_const
, const_type_id
and
(on unsupported targets) const_collections_with_hasher
.
Examples
Static variables in a generic context:
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Associating data with a type:
;
;
;
use ;
.unwrap;
.unwrap;
assert_eq!;
assert_eq!;