rust-i18n-derive
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.
🚀 Features
- Type-Safe Keys: Use Enum variants (e.g.,
Label::Login) instead of error-prone string literals. - Centralized Mapping: Keep the association between code and translation keys in one place.
- Compile-time Enforcement: The macro ensures that every enum variant has a mapped key via
#[tag("...")]. - Helper Methods: Automatically implements
.key()and.localize()methods for your Enums.
📖 Usage
-
Setup
rust-i18nEnsure you have initialized
rust-i18nin your project root (usually inlib.rsormain.rs), pointing to your locales directory:// Load I18n macro (from rust-i18n crate) i18n!; -
Derive
LocalizedImport the trait and derive macro, then annotate your enum variants with
#[tag("...")].use Localized;
🛠 How it works
The macro generates an implementation of the Localized trait for your Enum.
For the example above, it generates code equivalent to:
⚠️ Error Handling
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,
| ^^^^^
🤝 Contribution
Contributions are welcome! Please feel free to submit a Pull Request or open an issue on GitHub.
📄 License
This project is licensed under the MIT License.