Structs में Lifetimes
In this page:
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
// 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);
}
Login to try C/C++/Java/PHP code in the editor
Methods on a Struct with a Lifetime
एक lifetime parameter वाले struct के लिए एक impl block को वह lifetime declare और दोहराना चाहिए, methods को borrowed field के साथ बिल्कुल किसी और की तरह काम करने देते हुए।
उदाहरण: Methods on a Struct with a Lifetime
// 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());
}
Login to try C/C++/Java/PHP code in the editor
Instances Cannot Outlive Their Data
Compiler गारंटी देता है कि एक reference रखने वाला struct instance उस data के scope से बाहर जाने के बाद उपयोग नहीं हो सकता जिसे यह reference करता है, dangling struct fields को पूरी तरह रोकते हुए।
उदाहरण: Instances Cannot Outlive Their Data
// 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);
}
Login to try C/C++/Java/PHP code in the editor
Avoiding Lifetimes with Owned Data
अगर कोई struct अपना data own करता है (उदाहरण के लिए &str के बजाय String उपयोग करते हुए) इसे बिल्कुल कोई lifetime parameter नहीं चाहिए, एक छोटी allocation cost के बदले simpler code के लिए।
उदाहरण: Avoiding Lifetimes with Owned Data
// 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);
}
Login to try C/C++/Java/PHP code in the editor
- struct पर खुद एक lifetime parameter declare किए बिना किसी struct field में एक reference store करने की कोशिश करना, जो compile होने में fail होता है।
- यह मान लेना कि एक reference रखने वाला struct उस data से ज़्यादा जी सकता है जिस पर वह reference point करता है -- compiler इसके विपरीत enforce करता है।
- यह भूल जाना कि lifetime parameter वाले किसी struct के लिए एक
implblock को भी वह 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 के लिए
implblocks को उस एक जैसी 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: