← Back to Rust Course | Chapter 15: Cargo, Testing & Best Practices | Lesson 8 of 8

Idiomatic Rust लिखना

Idiomatic Rust का मतलब है code उस तरह लिखना जैसे experienced Rust programmers naturally लिखते, language की अपनी strengths उपयोग करते हुए उनसे लड़ने के बजाय।

Prefer Iterators Over Manual Loops

Idiomatic Rust अक्सर transformations को .map() और .filter() जैसे iterator adapters से express करता है बजाय mutable accumulator variables वाले manually लिखे loops के, क्योंकि यह ज़्यादा declarative और कम error-prone है।

उदाहरण: Prefer Iterators Over Manual Loops

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `numbers`, set to `vec![1, 2, 3, 4, 5]`
    let numbers = vec![1, 2, 3, 4, 5];
    // Declare an immutable variable `sum_of_squares` (an integer), set to `numbers.iter().map(|n| n * n).sum()`
    let sum_of_squares: i32 = numbers.iter().map(|n| n * n).sum();
    // Print "{}" to the console, substituting in `sum_of_squares` (with a trailing newline)
    println!("{}", sum_of_squares);
}

Borrow Instead of Clone When Possible

एक borrow-checker complaint से बचने के लिए .clone() तक पहुंचना आमतौर पर एक संकेत है कि code को इसके बजाय borrow करने के लिए restructure किया जा सकता था, अनावश्यक memory allocation और copying से बचते हुए।

उदाहरण: Borrow Instead of Clone When Possible

markup
// Define the function `print_length` taking `s`
fn print_length(s: &str) {
    // Print "Length: {}" to the console, substituting in `s.len()` (with a trailing newline)
    println!("Length: {}", s.len());
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `text`, set to `String::from("idiomatic")`
    let text = String::from("idiomatic");
    print_length(&text);
    // Print "Still usable: {}" to the console, substituting in `text` (with a trailing newline)
    println!("Still usable: {}", text);
}

Use the Type System to Prevent Bugs

Idiomatic Rust Option, Result, और enums पर निर्भर करता है invalid states को represent करना असंभव बनाने के लिए, bugs की पूरी categories को runtime checks के बजाय compile time पर पकड़ते हुए।

उदाहरण: Use the Type System to Prevent Bugs

markup
// Define an enum `PaymentStatus` listing its possible variants
enum PaymentStatus {
    Pending,
    Completed(f64),
    Failed(String),
}

// Define the function `describe` taking `status` and returning a String
fn describe(status: PaymentStatus) -> String {
    // Match on `status` and branch by pattern
    match status {
        PaymentStatus::Pending => String::from("still pending"),
        PaymentStatus::Completed(amount) => format!("completed for ${}", amount),
        PaymentStatus::Failed(reason) => format!("failed: {}", reason),
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Print "{}" to the console, substituting in `describe(PaymentStatus::Completed(49.99))` (with a trailing newline)
    println!("{}", describe(PaymentStatus::Completed(49.99)));
}

Listen to the Compiler

Rust compiler की warnings, जैसे एक unused mut या एक unused variable, आमतौर पर एक genuine simplification opportunity की ओर point कर रही होती हैं, और idiomatic code उन्हें suppress करने के बजाय seriously लेता है।

उदाहरण: Listen to the Compiler

markup
fn main() {
    let value = 100; // no mut needed since it is never reassigned
    println!("Clean, warning-free code: {}", value);
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Borrow checker से निपटने से बचने के लिए हर जगह .clone() overuse करना, code को सही से borrow करने के लिए restructure करने के बजाय।
  2. उन tasks के लिए verbose manual loops लिखना जिन्हें idiomatic Rust .map()/.filter() जैसे iterator adapters से express करता।
  3. Compiler warnings (जैसे unused mut या dead code) को नज़रअंदाज़ करना बजाय उन्हें cleaner code की ओर helpful hints मानने के।
चैप्टर सारांश
  • Idiomatic Rust manual loops की तुलना में iterator adapters पसंद करता है जब वे वही logic ज़्यादा clearly express करते हैं।
  • Cloning की तुलना में borrowing पसंद करना अनावश्यक allocations से बचाता है और code को Rust की ownership philosophy के करीब रखता है।
  • Type system (जैसे Option/Result) का लाभ उठाकर invalid states को unrepresentable बनाना अच्छे Rust code की एक पहचान है।
  • Compiler warnings पर ध्यान देना अक्सर code को simplify या correct करने के मौके उजागर करता है।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.