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
More of Rust
- How to use regex to match a group in Rust?
- How to use regex to match a double quote in Rust?
- How to parse JSON string in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to replace strings using Rust regex?
- Regex example to match multiline string in Rust?
- How to get a capture group using Rust regex?
- How to use groups in a Rust regex?
- How to split a string by regex in Rust?
- How to convert a u8 slice to a hex string in Rust?
See more codes...