macro_rules! static_map {
(constants of type $ty:ty: $($key:expr => $val:expr),*$(,)?) => { ... };
(of type $ty:ty: $($tt:tt)*) => { ... };
($($tt:tt)*) => { ... };
}
Expand description
Macro to create a StaticMap.
§Example
let map = static_map! {
false => 0,
true => 0,
};
§Variants
This macro has three variants:
-
macro_rules! static_map { ($($tt:tt)*) => { /* ... */ } }
The body of the macro invocation should be the body of a match statement. It will be called once for each possible variant. For example:
let map: StaticMap<u8, u32> = static_map! { n if n % 2 == 0 => n as u32 / 2, n => 3 * n as u32 + 1, };
Disadvantages:
-
Cannot be used in constants or statics.
-
It must be possible to move out of the values on the right-hand-side. The following example does not compile:
ⓘlet on_false = "this is false".to_string(); let on_true = "this is true".to_string(); let map = static_map! { false => on_false, true => on_true, };
-
-
macro_rules! static_map { (of type $ty:ty: $($tt:tt)*) => { /* ... */ } }
The body of the macro invocation should be the body of a match statement. It will be called once for each possible variant. For example:
#[derive(Linearize)] #[linearize(const)] enum Key { False, True, } const MAP: StaticMap<Key, u32> = static_map! { of type Key: Key::False => 0, Key::True => 1, }; assert_eq!(MAP[Key::False], 0); assert_eq!(MAP[Key::True], 1);
Disadvantages:
- Requires rust 1.83 or later.
- The key type must be a concrete type. This variant cannot be used in code that is generic over the key type.
- Cannot be used with keys containing any of the core types
bool
,u8
, etc. - Can only be used with keys that use the derive macro and enable the
linearize(const)
feature. - It must be possible to move out of the values on the right-hand-side.
Advantages:
- Can be used in constants and statics.
-
macro_rules! static_map { (constants of type $ty:ty: $($key:expr => $val:expr),*$(,)?) => { /* ... */ } }
The body of the macro invocation should be an exhaustive map from constant keys to values. For example:
#[derive(Linearize)] #[linearize(const)] enum Key { False, True, } let on_false = "this is false".to_string(); let on_true = "this is true".to_string(); let map = static_map! { constants of type Key: Key::False => on_false, Key::True => on_true, }; assert_eq!(map[Key::False], "this is false"); assert_eq!(map[Key::True], "this is true");
Disadvantages:
- Requires rust 1.83 or later.
- The key type must be a concrete type. This variant cannot be used in code that is generic over the key type.
- Cannot be used with keys containing any of the core types
bool
,u8
, etc. - Can only be used with keys that use the derive macro and enable the
linearize(const)
feature. - The keys must be constants.
Advantages:
- Can be used in constants and statics.
- Each value will only be accessed once, allowing them to move out of variables.