| Crates.io | rust-i18n-derive |
| lib.rs | rust-i18n-derive |
| version | 1.0.1 |
| created_at | 2025-12-30 18:57:46.194655+00 |
| updated_at | 2025-12-30 22:24:10.326497+00 |
| description | A Rust derive macro for internationalization (i18n) support. |
| homepage | |
| repository | https://github.com/xairaven/rust-i18n-derive |
| max_upload_size | |
| id | 2013151 |
| size | 9,550 |
A concise, type-safe derive macro for rust-i18n key mapping.
rust-i18n-derive provides a convenient way to bind Rust Enums to your translation keys. Instead of using raw string literals (like "menu.open") throughout your codebase, you can map them once in an Enum definition and use the generated methods to retrieve keys or localized strings.
This crate works alongside rust-i18n, acting as a bridge between strongly typed Rust structures and localization files.
Label::Login) instead of error-prone string literals.#[tag("...")]..key() and .localize() methods for your Enums.Setup rust-i18n
Ensure you have initialized rust-i18n in your project root (usually in lib.rs or main.rs), pointing to your locales directory:
// Load I18n macro (from rust-i18n crate)
rust_i18n::i18n!("locales");
Derive Localized
Import the trait and derive macro, then annotate your enum variants with #[tag("...")].
use rust_i18n_derive::Localized;
#[derive(Debug, Localized)]
pub enum MainMenu {
#[tag("menu.file.open")]
Open,
#[tag("menu.file.save")]
Save,
#[tag("menu.help.about")]
About,
}
fn main() {
let item = MainMenu::Open;
// 1. Get the raw key (useful for logging or debugging)
assert_eq!(item.key(), "menu.file.open");
// 2. Get the localized string (uses rust_i18n::t! under the hood)
// Assuming you have a locale file where "menu.file.open" = "Open File"
println!("{}", item.localize());
}
The macro generates an implementation of the Localized trait for your Enum.
For the example above, it generates code equivalent to:
impl Localized for MainMenu {
fn key(&self) -> &'static str {
match self {
Self::Open => "menu.file.open",
Self::Save => "menu.file.save",
Self::About => "menu.help.about",
}
}
fn localize(&self) -> String {
rust_i18n::t!(self.key())
}
}
The macro validates your code at compile time. If you forget to add a #[tag("...")] attribute to a variant, the compiler will panic with a helpful error message pointing exactly to the missing line:
error: Missing #[tag("...")] for variant `Close`
--> src/main.rs:15:5
|
15 | Close,
| ^^^^^
Contributions are welcome! Please feel free to submit a Pull Request or open an issue on GitHub.
This project is licensed under the MIT License.