← Back to Rust Course | Chapter 12: Lifetimes | Lesson 6 of 6

Lifetime Elision के Rules

Lifetime elision Rust का चुपचाप आपके लिए obvious lifetime labels भरना है, ताकि आपको हर बार इन्हें हाथ से लिखना न पड़े।
Syntax
rust
fn function_name(param: &Type) -> &Type { ... }   // one input: elided

impl StructName {
    fn method_name(&self) -> &Type { ... }          // uses self's lifetime
}

fn function_name<'a>(a: &'a Type, b: &'a Type) -> &'a Type { ... }

Elision Rule: One Input, One Output

जब किसी function में बिल्कुल एक reference parameter हो और यह एक reference return करे, compiler अपने आप मान लेता है कि output lifetime input से मेल खाता है, किसी annotation की ज़रूरत नहीं।

उदाहरण: Elision Rule: One Input, One Output

markup
// Define the function `first_word` taking `s` and returning a string slice
fn first_word(s: &str) -> &str {
    // Match on `s.find(' ')` and branch by pattern
    match s.find(' ') {
        Some(i) => &s[..i],
        None => s,
    }
}

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

Elision in Methods Using self

&self लेने वाले methods के लिए, elision rules return type में किसी elided reference को self का lifetime assign करते हैं, यही कारण है कि इतने सारे getter-style methods को कोई explicit lifetime syntax नहीं चाहिए।

उदाहरण: Elision in Methods Using self

markup
// Define a struct `Container` to group related fields together
struct Container {
    text: String,
}

// Implement methods on `Container`
impl Container {
    // Define the function `get_text` taking `&self` and returning a string slice
    fn get_text(&self) -> &str {
        &self.text
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `c`, set to `Container { text: String::from("elided lifetime works here") }`
    let c = Container { text: String::from("elided lifetime works here") };
    // Print "{}" to the console, substituting in `c.get_text()` (with a trailing newline)
    println!("{}", c.get_text());
}

When Elision Is Not Enough

एक से ज़्यादा reference parameter और कोई self न होने पर, compiler guess नहीं कर सकता कि output किस input से related है, इसलिए एक explicit lifetime annotation ज़रूरी हो जाता है।

उदाहरण: When Elision Is Not Enough

markup
fn pick_longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    // Check whether `a.len() > b.len() { a } else { b }`
    if a.len() > b.len() { a } else { b }
}

// Entry point: execution of the program starts here
fn main() {
    // Print "{}" to the console, substituting in `pick_longer("short", "much longer")` (with a trailing newline)
    println!("{}", pick_longer("short", "much longer"));
}

Elision Reduces Boilerplate

इन rules के कारण, references वाले everyday Rust functions की भारी बहुमत को शून्य explicit lifetime syntax चाहिए, और annotations सिर्फ तब दिखते हैं जब relationship genuinely ambiguous हो।

उदाहरण: Elision Reduces Boilerplate

markup
// Define the function `trim_and_return` taking `s` and returning a string slice
fn trim_and_return(s: &str) -> &str {
    s.trim()
}

// Entry point: execution of the program starts here
fn main() {
    // Print "[{}]" to the console, substituting in `trim_and_return("   padded   ")` (with a trailing newline)
    println!("[{}]", trim_and_return("   padded   "));
}
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. साधारण functions के लिए explicit lifetime annotations लिखना जिन्हें elision rules पहले से अपने आप handle करते हैं, अनावश्यक noise जोड़ते हुए।
  2. यह मान लेना कि elision हर function shape पर लागू होता है -- यह सिर्फ common patterns के एक specific set को cover करता है; इससे ज़्यादा complex किसी भी चीज़ को अब भी explicit annotations चाहिए।
  3. यह भूल जाना कि &self लेने वाला method तीसरे elision rule से किसी elided return reference के लिए self का lifetime उपयोग करता है।
चैप्टर सारांश
  • Lifetime elision rules compiler को explicit annotations के बिना आम, simple function signatures के लिए lifetimes infer करने देते हैं।
  • Rule एक: हर reference parameter को अपना inferred lifetime मिलता है।
  • Rule दो: अगर बिल्कुल एक input lifetime है, यह सभी elided output lifetimes को assign किया जाता है।
  • Rule तीन: methods के लिए, &self का lifetime elided output lifetimes को assign किया जाता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 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.