Crates.io | enum_dict |
lib.rs | enum_dict |
version | 0.2.0 |
created_at | 2025-09-15 16:20:26.374582+00 |
updated_at | 2025-09-16 13:58:28.387921+00 |
description | Efficient enum-indexed dictionaries. |
homepage | |
repository | https://github.com/shigma/enum-dict |
max_upload_size | |
id | 1840281 |
size | 19,361 |
A Rust library for efficient enum-indexed dictionaries.
Add to your Cargo.toml
:
[dependencies]
enum_dict = { version = "0.1", features = ["full"] }
use enum_dict::{DictKey, FromStr, required_dict, optional_dict};
#[derive(DictKey, FromStr)]
enum Color {
Red,
Green,
Blue,
}
fn main() {
// `RequiredDict` - all keys must have values
let mut colors = required_dict! {
Color::Red => "#FF0000",
Color::Green => "#00FF00",
Color::Blue => "#0000FF",
};
// Direct indexing - no `.get()` needed!
println!("Red hex: {}", colors[Color::Red]);
// Mutable access
colors[Color::Red] = "#FF0001";
// `OptionalDict` - keys may or may not have values
let favorite_colors = optional_dict! {
Color::Blue => "Sky Blue",
};
// Returns `Option<&str>`
if let Some(favorite) = favorite_colors[Color::Blue] {
println!("Favorite blue: {}", favorite);
}
}
With the serde feature enabled, RequiredDict
and OptionalDict
can be serialized and deserialized using serde:
use enum_dict::{DictKey, RequiredDict};
use serde::{Serialize, Deserialize};
#[derive(DictKey)]
enum Locale {
EN,
FR,
JP,
ZH,
}
#[derive(Serialize, Deserialize)]
struct I18nMessage {
translations: RequiredDict<Locale, String>,
}
Extra keys in the serialized data are ignored during deserialization.
enum_dict
?Compared to traditional HashMap
approach, enum_dict
uses Vec
under the hood, allowing for:
dict[key]
instead of dict.get(&key)
.