-
Notifications
You must be signed in to change notification settings - Fork 121
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
No way to map enum? #196
Comments
I have the same problem why not support enum as key map? |
No, being a preprocessor/macro means that it needs to have direct access to the value of the key (phf is "reading" the keys from the source code), there's no way for it to access rust types & values indirectly, it needs to be a simple rust literal. phf needs the value of the key to hash it at compile time. Take my use case for example: I need to check if an uuid is contained in a set of "hardcoded" uuids. My first approach was to define a const array and use binary search for performance, but that requires that the array is sorted by hand by the developer. phf is easier to use (no need to sort by hand) but now i can't just use |
dup of #188 ? |
If you want to use enum keys, there is the enum-map crate. You can use The #[derive(Debug, Enum)]
enum Example {
A,
B,
C,
D,
}
// Initialize the map with the keys A and B defined, but C and D are not defined.
let mut map = enum_map! {
Example::A => Some("foo"),
Example::B => Some("bar"),
_ => None,
};
// This is the same as `map.get(&Example::C)` in a normal hash map.
let value = &map[Example::C];
// This is the same as `map.insert(Example::C, "qux");` in a normal hash map.
map[Example::C] = Some("qux"); |
Does this work with static constant declarations (because that's the whole point of I think the answer is no, which means this is not a good solution for someone having difficulty declaring static enum maps using |
@thomasmost Unfortunately it cannot be used directly in a However, using use once_cell::sync::Lazy;
use enum_map::{Enum, EnumMap, enum_map};
#[derive(Debug, Enum)]
enum Example {
A,
B,
C,
D,
}
static FOO: Lazy<EnumMap<Example, Option<&'static str>>> = Lazy::new(|| enum_map! {
Example::A => Some("foo"),
Example::B => Some("bar"),
_ => None,
});
fn main() {
println!("{:?}", FOO[Example::A]);
println!("{:?}", FOO[Example::B]);
println!("{:?}", FOO[Example::C]);
} And using |
Two issues that make enum-map not ideal for this:
Ideally a proc macro could have access to constant values like primitive enums (unfortunately |
Hi, it's not possible to map with enum keys?
The text was updated successfully, but these errors were encountered: