### Rust: Complete Application Example with Translation System Source: https://context7.com/0ldm0s/rat_quikc_lang/llms.txt A full-featured Rust application example showcasing the translation system's setup, initialization, language switching, error message display, and translation coverage reporting. It utilizes the rat_quikc_lang crate and standard library file operations. This example includes setup and cleanup of translation files. ```rust use rat_quikc_lang::* use std::fs; fn main() -> Result<(), Box> { // Setup translation files setup_translation_files()?; // Initialize translation system load_translations("app_lang")?; // Application startup println!("=== Application Starting ==="); println!("Detected language: {}", current_language()); // Display UI in current language display_main_menu(); // User changes language preference println!("\n=== User Changes Language to Chinese ==="); set_language("zh-CN")?; display_main_menu(); // Display error messages println!("\n=== Error Handling Examples ==="); display_error_messages(); // Show translation coverage println!("\n=== Translation Coverage Report ==="); show_translation_coverage(); // Cleanup fs::remove_dir_all("app_lang")?; Ok(()) } fn display_main_menu() { println!("\n{}", t("ui.main_menu")); println!("1. {}", t("menu.new_file")); println!("2. {}", t("menu.open_file")); println!("3. {}", t("menu.save_file")); println!("4. {}", t("menu.exit")); println!("\nButtons:"); println!(" [{}] [{}]", t("buttons.ok"), t("buttons.cancel")); } fn display_error_messages() { let errors = vec![ "errors.file_not_found", "errors.permission_denied", "errors.network_timeout", ]; for error_key in errors { if has_translation(error_key) { println!(" ⚠ {}", t(error_key)); } } } fn show_translation_coverage() { let all_keys = get_all_keys(); println!("Total keys: {}", all_keys.len()); for key in all_keys.iter().take(5) { let langs = get_supported_languages(key); println!(" {} -> {} languages", key, langs.len()); } } fn setup_translation_files() -> Result<(), Box> { fs::create_dir_all("app_lang/errors")?; fs::create_dir_all("app_lang/menu")?; // English translations fs::write("app_lang/errors/en_US.toml", r#"file_not_found = "File not found" permission_denied = "Permission denied" network_timeout = "Network connection timeout" "#)?; fs::write("app_lang/menu/en_US.toml", r#"new_file = "New File" open_file = "Open File" save_file = "Save File" exit = "Exit Application" "#)?; // Chinese translations fs::write("app_lang/errors/zh_CN.toml", r#"file_not_found = "文件未找到" permission_denied = "权限被拒绝" network_timeout = "网络连接超时" "#)?; fs::write("app_lang/menu/zh_CN.toml", r#"new_file = "新建文件" open_file = "打开文件" save_file = "保存文件" exit = "退出应用" "#)?; // UI translations (single file format) fs::write("app_lang/ui.toml", r#"[en_US] main_menu = "Main Menu" [zh_CN] main_menu = "主菜单" "#)?; // Buttons (single file format) fs::write("app_lang/buttons.toml", r#"[en_US] ok = "OK" cancel = "Cancel" [zh_CN] ok = "确定" cancel = "取消" "#)?; Ok(()) } ``` -------------------------------- ### Shell: Example Cargo Command Source: https://github.com/0ldm0s/rat_quikc_lang/blob/master/README.md Provides the command-line instruction to run the basic usage example of the rat_quikc_lang project using Cargo. ```bash cargo run --example basic_usage ``` -------------------------------- ### TOML: Common Translations File Example Source: https://github.com/0ldm0s/rat_quikc_lang/blob/master/README.md Provides an example of a TOML file structured for common translations, likely used in the folder-based organization. It demonstrates nested key structures for organizing related phrases. ```toml welcome = "欢迎" buttons.save = "保存" buttons.cancel = "取消" ``` -------------------------------- ### TOML: Single File Translations Example Source: https://github.com/0ldm0s/rat_quikc_lang/blob/master/README.md Shows an example of a single TOML file containing translations for multiple languages. Each language is a top-level key, with nested keys for specific translation strings. ```toml [zh_CN] title = "标题" exit = "退出" [en_US] title = "Title" exit = "Exit" ``` -------------------------------- ### Get Supported Languages for a Key in Rust Source: https://context7.com/0ldm0s/rat_quikc_lang/llms.txt Shows how to find out which languages a specific translation key is available in using `get_supported_languages`. The example iterates through supported languages to display the translation, checks coverage for multiple keys, and identifies keys missing specific target languages. ```rust use rat_quikc_lang::*; fn main() -> Result<(), Box> { load_translations("lang")?; // Get supported languages for a key let languages = get_supported_languages("common.welcome"); println!("Languages with 'common.welcome' translation:"); for lang in &languages { set_language(lang)?; println!(" {}: {}", lang, t("common.welcome")); } // Check translation coverage let keys_to_check = vec!["common.welcome", "ui.title", "common.buttons.save"]; for key in keys_to_check { let langs = get_supported_languages(key); println!("\n{} is available in {} languages:", key, langs.len()); println!(" Languages: {:?}", langs); } // Find missing translations let all_keys = get_all_keys(); let expected_languages = vec!["zh-CN", "en-US"]; for key in all_keys { let available = get_supported_languages(&key); let missing: Vec<_> = expected_languages.iter() .filter(|lang| !available.contains(&lang.to_string())) .collect(); if !missing.is_empty() { println!("{} missing in: {:?}", key, missing); } } Ok(()) } ``` -------------------------------- ### Get All Translation Keys in Rust Source: https://context7.com/0ldm0s/rat_quikc_lang/llms.txt Illustrates how to retrieve a list of all available translation keys using `get_all_keys`. The example shows how to count keys, iterate through them, and filter them by module or content (e.g., keys starting with 'common.' or containing 'button'). ```rust use rat_quikc_lang::*; fn main() -> Result<(), Box> { load_translations("lang")?; // Get all translation keys let all_keys = get_all_keys(); println!("Total translation keys: {}", all_keys.len()); println!("\nAvailable keys:"); for key in &all_keys { println!(" - {}", key); } // Filter keys by module let common_keys: Vec<_> = all_keys.iter() .filter(|k| k.starts_with("common.")) .collect(); println!("\nCommon module keys:"); for key in common_keys { println!(" - {}: {}", key, t(key)); } // Export keys for documentation let button_keys: Vec<_> = all_keys.iter() .filter(|k| k.contains("button")) .collect(); println!("\nButton-related keys:"); for key in button_keys { println!(" - {}", key); } Ok(()) } ``` -------------------------------- ### TOML: Example Folder Structure for Translations Source: https://github.com/0ldm0s/rat_quikc_lang/blob/master/README.md Illustrates the folder-based organization for multilingual translation files using TOML format. It shows how translations can be separated by language and category (e.g., common, errors), facilitating modularity and management of language resources. ```toml lang/ ├── common/ │ ├── zh_CN.toml │ ├── en_US.toml │ └── ja_JP.toml └── errors/ ├── zh_CN.toml └── en_US.toml ``` -------------------------------- ### Rust: Comprehensive Error Handling for File Operations Source: https://context7.com/0ldm0s/rat_quikc_lang/llms.txt Demonstrates robust error handling for various file operations within the rat_quikc_lang library. It covers scenarios like directory not found, file load errors, and parsing errors (invalid TOML format), ensuring graceful failure and informative messages. This example requires the rat_quikc_lang crate. ```rust use rat_quikc_lang::* use rat_quikc_lang::LangError; fn main() { // Handle directory not found match load_translations("nonexistent_dir") { Ok(_) => println!("Loaded successfully"), Err(LangError::DirectoryNotFound { path }) => { eprintln!("Error: Directory not found at {}", path); eprintln!("Please create the directory first"); } Err(e) => eprintln!("Other error: {}", e), } // Handle file load errors match load_translations("/invalid/path") { Ok(_) => println!("Loaded successfully"), Err(LangError::FileLoadError { path, message }) => { eprintln!("Failed to load file {}: {}", path, message); } Err(e) => eprintln!("Error: {}", e), } // Handle parse errors (invalid TOML) use std::fs; fs::create_dir_all("bad_lang/common").ok(); fs::write("bad_lang/common/en_US.toml", "invalid toml content {{{").ok(); match load_translations("bad_lang") { Ok(_) => println!("Loaded"), Err(LangError::ParseError { file, message }) => { eprintln!("Parse error in {}: {}", file, message); } Err(e) => eprintln!("Error: {}", e), } // Graceful handling if let Err(e) = load_translations("lang") { eprintln!("Failed to load translations: {}", e); eprintln!("Falling back to default language"); } } ``` -------------------------------- ### TOML: Example Single File Translation Structure Source: https://github.com/0ldm0s/rat_quikc_lang/blob/master/README.md Presents an alternative single-file organization for translation data using TOML. This structure allows multiple languages to be defined within a single file, useful for smaller projects or related UI elements. ```toml lang/ ├── ui.toml # Contains translations for multiple languages └── menu.toml # Contains translations for multiple languages ``` -------------------------------- ### Reload Translation Files at Runtime in Rust Source: https://context7.com/0ldm0s/rat_quikc_lang/llms.txt Demonstrates hot-reloading of translation files using the `reload` function. This allows updating translations dynamically without restarting the application. The example shows modifying an existing file, adding a new language file, and then triggering reloads to apply the changes. ```rust use rat_quikc_lang::*; use std::fs; fn main() -> Result<(), Box> { // Initial load load_translations("lang")?; println!("Initial translation: {}", t("common.welcome")); // Simulate translation file update fs::write("lang/common/en_US.toml", r#" welcome = "Welcome Back!" buttons.save = "Save Changes" buttons.cancel = "Cancel Operation" "#)?; // Reload translations to pick up changes reload("lang")?; println!("After reload: {}", t("common.welcome")); // Output: Welcome Back! // Add new translation at runtime fs::write("lang/common/fr_FR.toml", r#" welcome = "Bienvenue" buttons.save = "Sauvegarder" buttons.cancel = "Annuler" "#)?; // Reload to include new language reload("lang")?; set_language("fr-FR")?; println!("French translation: {}", t("common.welcome")); // Output: Bienvenue Ok(()) } ``` -------------------------------- ### Set and Get Current Language in Rust Source: https://context7.com/0ldm0s/rat_quikc_lang/llms.txt Allows dynamic switching between languages and querying the currently active language. The `set_language` function normalizes language codes (e.g., "zh", "zh_cn", "zh-cn" all become "zh-CN") and is case-insensitive. Language detection can be automatic via environment variables. ```rust use rat_quikc_lang::*; fn main() -> Result<(), Box> { load_translations("lang")?; // Get current language (auto-detected from LANG env var) let current = current_language(); println!("Initial language: {}", current); // Set to Chinese (supports multiple formats) set_language("zh-CN")?; println!("Changed to: {}", current_language()); println!("Welcome: {}", t("common.welcome")); // Output: 欢迎 // Language codes are normalized: zh, zh_cn, zh-cn all become zh-CN set_language("en")?; println!("Changed to: {}", current_language()); println!("Welcome: {}", t("common.welcome")); // Output: Welcome // Case-insensitive language switching set_language("EN_US")?; println!("Changed to: {}", current_language()); // Output: en-US Ok(()) } ``` -------------------------------- ### Cargo TOML: Project Dependencies Source: https://github.com/0ldm0s/rat_quikc_lang/blob/master/README.md Lists the dependencies required for the rat_quikc_lang project, including the core 'rat_embed_lang', 'toml' for parsing TOML files, 'serde' for serialization/deserialization, and 'thiserror' for error handling. ```toml [dependencies] rat_embed_lang = "0.1.0" toml = "0.8" serde = { version = "1.0", features = ["derive"] } thiserror = "1.0" ``` -------------------------------- ### Load Translation Files in Rust Source: https://context7.com/0ldm0s/rat_quikc_lang/llms.txt Initializes the translation system by loading TOML translation files from a specified directory. It supports both folder-based (lang/module/language.toml) and single-file (lang/module.toml) organization. Errors during loading are returned as LangError. Requires `std::fs` for file operations. ```rust use rat_quikc_lang::*; use std::fs; fn main() -> Result<(), Box> { // Create folder-based translation structure fs::create_dir_all("lang/common")?; fs::write("lang/common/zh_CN.toml", r#" welcome = "欢迎" buttons.save = "保存" buttons.cancel = "取消" "#)?; fs::write("lang/common/en_US.toml", r#" welcome = "Welcome" buttons.save = "Save" buttons.cancel = "Cancel" "#)?; // Create single-file translation fs::write("lang/ui.toml", r#" [zh_CN] title = "标题" exit = "退出" [en_US] title = "Title" exit = "Exit" "#)?; // Load all translations - returns Result<(), LangError> load_translations("lang")?; println!("Translation system initialized successfully"); println!("Current language: {}", current_language()); Ok(()) } ``` -------------------------------- ### Rust: Load and Use Translations with rat_quikc_lang Source: https://github.com/0ldm0s/rat_quikc_lang/blob/master/README.md Demonstrates the core API usage of rat_quikc_lang, including loading translation files from a directory, retrieving translated strings using a key, setting the current language, and printing the current language. It requires the 'rat_quikc_lang' crate and handles potential errors during loading or setting the language. ```rust use rat_quikc_lang::*; fn main() -> Result<(), Box> { // Load translation files from the 'lang' directory load_translations("lang")?; // Get a translation for the key "common.welcome" println!("{}", t("common.welcome")); // Set the current language to Simplified Chinese set_language("zh-CN")?; // Get and print the current language println!("当前语言: {}", current_language()); Ok(()) } ``` -------------------------------- ### Check Translation Existence in Rust Source: https://context7.com/0ldm0s/rat_quikc_lang/llms.txt Demonstrates how to check if a translation key exists before accessing it using the `has_translation` function. This prevents runtime errors and allows for conditional UI rendering or logging. It also shows iterating through a list of keys to validate their existence. ```rust use rat_quikc_lang::*; fn main() -> Result<(), Box> { load_translations("lang")?; // Check if translation exists if has_translation("common.welcome") { println!("Welcome message: {}", t("common.welcome")); } else { println!("Welcome translation not available"); } // Use for conditional UI elements let show_advanced = has_translation("settings.advanced"); if show_advanced { println!("Advanced settings available"); } // Validate keys before displaying let keys_to_check = vec![ "common.welcome", "common.goodbye", "ui.title", "invalid.key", ]; for key in keys_to_check { let exists = has_translation(key); println!("{}: {}", key, if exists { "✓" } else { "✗" }); } Ok(()) } ``` -------------------------------- ### Retrieve Translations in Rust Source: https://context7.com/0ldm0s/rat_quikc_lang/llms.txt Retrieves translated text for a given key in the currently active language. Supports nested keys using dot notation. If a translation key is not found, it returns the key wrapped in brackets (e.g., "[nonexistent.key]"). Requires translation files to be loaded first. ```rust use rat_quikc_lang::*; fn main() -> Result<(), Box> { // Initialize translation system load_translations("lang")?; // Basic translation retrieval let welcome = t("common.welcome"); println!("{}", welcome); // Output depends on current language // Nested keys using dot notation let save_button = t("common.buttons.save"); let cancel_button = t("common.buttons.cancel"); println!("Button labels:"); println!(" Save: {}", save_button); println!(" Cancel: {}", cancel_button); // Single-file module translations let ui_title = t("ui.title"); let exit_button = t("ui.exit"); println!("\nUI Elements:"); println!(" Title: {}", ui_title); println!(" Exit: {}", exit_button); // Missing key returns [key] let missing = t("nonexistent.key"); println!("\nMissing key: {}", missing); // Output: [nonexistent.key] Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.