Ownership और Borrowing
Rust Lifetimes Explained
Tell the compiler how long a returned reference stays valid with 'a.
आप क्या सीखेंगे
- What a lifetime is
- Annotating with 'a
- Lifetimes in structs
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str
- 1
a: &'a strinput - 2
b: &'a strinput - 3
-> &'a strvalid as long as both inputs
References must not outlive their data
A lifetime describes how long a reference is valid. Most of the time the compiler works it out. When a function returns a reference that could come from more than one parameter, you name the lifetime with 'a.
The signature of longest says that the result lives as long as both inputs do. subtitle is a string literal, which lives for the whole program, so result is still valid after the inner block. A struct that stores a reference needs a lifetime too.
मुख्य बातें
- Most lifetimes are worked out by the compiler.
- 'a links the result to the inputs.
- A struct that stores a reference needs a lifetime.
चलने योग्य Rust उदाहरण
Rust
main.rs
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() {
a
} else {
b
}
}
struct Highlight<'a> {
text: &'a str,
}
fn main() {
let title = String::from("The Rust Book");
let result;
{
let subtitle = "2021 edition";
result = longest(&title, subtitle);
}
println!("longest: {result}");
let highlight = Highlight { text: &title[4..8] };
println!("highlight: {}", highlight.text);
}
longest: The Rust Book
highlight: Rustअभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज