Annotazioni di lifetime in Rust
Livello 4346 battiture
Le annotazioni di lifetime indicano al compilatore per quanto tempo i riferimenti devono essere validi l'uno rispetto all'altro.
Codice Rust
// 'a lega il risultato a entrambi gli input: vive quanto quello di durata più breve1fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { // Confronta le lunghezze in byte2 if x.len() > y.len() { // x è più lunga: viene restituita3 x4 } else { // Altrimenti (anche a parità di lunghezza) restituisce y5 y6 }7}8 // Punto di ingresso del programma9fn main() { // Due String possedute che vivono fino alla fine di main10 let s1 = String::from("long string is long");11 let s2 = String::from("short");12 // &String viene convertito automaticamente in &str13 let result = longest(&s1, &s2); // Stampa "Longest: long string is long"14 println!("Longest: {}", result);15 // Un letterale stringa ha il lifetime 'static16 let s3 = "static str"; // "static str" (10 byte) è più lunga di "another" (7 byte)17 let result2 = longest(s3, "another"); // Stampa "Longest: static str"18 println!("Longest: {}", result2);19}Output
Longest: long string is long Longest: static str
Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.
Simboli in questo codice
I simboli che digiti in questo codice Rust e quante volte compaiono.
"× 12(× 10)× 10:× 8;× 7{× 6}× 6,× 5&× 5=× 5