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

Structs में Lifetimes

एक struct जो एक borrowed value रखता है उसे भी अपना age label चाहिए, ताकि Rust गारंटी दे सके कि यह कभी उससे ज़्यादा नहीं जीता जिससे यह borrow कर रहा है।
Syntax
rust
struct Name<'a> {
    field: &'a str,
}

impl<'a> Name<'a> {
    fn method(&self) -> &str {
        self.field
    }
}

A Struct Holding a Reference

जब कोई struct field एक reference है, struct को खुद एक lifetime parameter चाहिए, यह सुनिश्चित करते हुए कि struct का कोई instance उस data से ज़्यादा नहीं जी सकता जिसे यह borrow करता है।

उदाहरण: A Struct Holding a Reference

markup
// Define a struct `Excerpt` to group related fields together
struct Excerpt<'a> {
    text: &'a str,
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `novel`, set to `String::from("Call me Ishmael. Some years ago...")`
    let novel = String::from("Call me Ishmael. Some years ago...");
    // Declare an immutable variable `first_sentence`, set to `novel.split('.').next().unwrap()`
    let first_sentence = novel.split('.').next().unwrap();
    // Declare an immutable variable `excerpt`, set to `Excerpt { text: first_sentence }`
    let excerpt = Excerpt { text: first_sentence };
    // Print "{}" to the console, substituting in `excerpt.text` (with a trailing newline)
    println!("{}", excerpt.text);
}

Methods on a Struct with a Lifetime

एक lifetime parameter वाले struct के लिए एक impl block को वह lifetime declare और दोहराना चाहिए, methods को borrowed field के साथ बिल्कुल किसी और की तरह काम करने देते हुए।

उदाहरण: Methods on a Struct with a Lifetime

markup
// Define a struct `Excerpt` to group related fields together
struct Excerpt<'a> {
    text: &'a str,
}

// Implement methods on `Excerpt`
impl<'a> Excerpt<'a> {
    // Define the function `announce` taking `&self` and returning a String
    fn announce(&self) -> String {
        format!("Excerpt: {}", self.text)
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `source`, set to `String::from("Rust is reliable and fast")`
    let source = String::from("Rust is reliable and fast");
    // Declare an immutable variable `excerpt`, set to `Excerpt { text: &source[0..4] }`
    let excerpt = Excerpt { text: &source[0..4] };
    // Print "{}" to the console, substituting in `excerpt.announce()` (with a trailing newline)
    println!("{}", excerpt.announce());
}

Instances Cannot Outlive Their Data

Compiler गारंटी देता है कि एक reference रखने वाला struct instance उस data के scope से बाहर जाने के बाद उपयोग नहीं हो सकता जिसे यह reference करता है, dangling struct fields को पूरी तरह रोकते हुए।

उदाहरण: Instances Cannot Outlive Their Data

markup
// Define a struct `Wrapper` to group related fields together
struct Wrapper<'a> {
    value: &'a i32,
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `number`, set to `42`
    let number = 42;
    // Declare an immutable variable `wrapped`, set to `Wrapper { value: &number }`
    let wrapped = Wrapper { value: &number };
    // Print "{}" to the console, substituting in `wrapped.value` (with a trailing newline)
    println!("{}", wrapped.value);
}

Avoiding Lifetimes with Owned Data

अगर कोई struct अपना data own करता है (उदाहरण के लिए &str के बजाय String उपयोग करते हुए) इसे बिल्कुल कोई lifetime parameter नहीं चाहिए, एक छोटी allocation cost के बदले simpler code के लिए।

उदाहरण: Avoiding Lifetimes with Owned Data

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

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `excerpt`, set to `OwnedExcerpt { text: String::from("No lifetime needed here") }`
    let excerpt = OwnedExcerpt { text: String::from("No lifetime needed here") };
    // Print "{}" to the console, substituting in `excerpt.text` (with a trailing newline)
    println!("{}", excerpt.text);
}
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. struct पर खुद एक lifetime parameter declare किए बिना किसी struct field में एक reference store करने की कोशिश करना, जो compile होने में fail होता है।
  2. यह मान लेना कि एक reference रखने वाला struct उस data से ज़्यादा जी सकता है जिस पर वह reference point करता है -- compiler इसके विपरीत enforce करता है।
  3. यह भूल जाना कि lifetime parameter वाले किसी struct के लिए एक impl block को भी वह lifetime दोहराना चाहिए, जैसे impl<'a> MyStruct<'a>।
चैप्टर सारांश
  • एक reference field रखने वाले struct को एक lifetime parameter declare करना चाहिए, जैसे struct Excerpt<'a> { text: &'a str }।
  • ऐसे struct का एक instance उस data से ज़्यादा नहीं जी सकता जिस पर इसकी reference field point करती है।
  • एक lifetime parameter वाले struct के लिए impl blocks को उस एक जैसी lifetime declare और दोहराना चाहिए।
  • Owned data store करना (जैसे &str के बजाय String) एक lifetime parameter की ज़रूरत से बचाता है, एक extra allocation की कीमत पर।
🔒

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.