Ownership e borrowing
Rust Lifetimes Explained
Tell the compiler how long a returned reference stays valid with 'a.
Cosa imparerai
- 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.
Punti chiave
- Most lifetimes are worked out by the compiler.
- 'a links the result to the inputs.
- A struct that stores a reference needs a lifetime.
Esempio Rust eseguibile
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: RustEsercitati
Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.
Hai finito questa lezione?
Segnala come imparata per tenere traccia dei tuoi progressi.
I tuoi progressi sono salvati in questo browser Accedi per conservarli su ogni dispositivo.
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
Tutte le sfide