rustHow to use enum as hashmap key in Rust
Enums in Rust can be used as hashmap keys by implementing the Eq and Hash traits. This can be done by adding #[derive(Eq, Hash)] to the enum definition. For example:
#[derive(Eq, Hash)]
enum Color {
Red,
Blue,
Green,
}
fn main() {
use std::collections::HashMap;
let mut colors = HashMap::new();
colors.insert(Color::Red, "red");
colors.insert(Color::Blue, "blue");
colors.insert(Color::Green, "green");
println!("{:?}", colors);
}
The output of this code is {Color::Red: "red", Color::Blue: "blue", Color::Green: "green"}. The #[derive(Eq, Hash)] annotation allows the enum to be used as a key in the hashmap.
Helpful links
Related
- How to create enum from string in Rust
- How to create enum from int in Rust
- How to compare enum in Rust
- Get certain enum value in Rust
- Enum as u8 in Rust
- How to get enum value in Rust
- Enum as u32 in Rust
- How to print enum in Rust
- How to get all enum values in Rust
- How to create enum from number in Rust
More of Rust
- How to replace a capture group using Rust regex?
- How to use Unicode in a regex in Rust?
- How to get a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to match whitespace with a regex in Rust?
- How to replace all matches using Rust regex?
- How to split a string with Rust regex?
- How to use 'or' in Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use regex with bytes in Rust?
See more codes...