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ù breve
1fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
// Confronta le lunghezze in byte
2 if x.len() > y.len() {
// x è più lunga: viene restituita
3 x
4 } else {
// Altrimenti (anche a parità di lunghezza) restituisce y
5 y
6 }
7}
8
// Punto di ingresso del programma
9fn main() {
// Due String possedute che vivono fino alla fine di main
10 let s1 = String::from("long string is long");
11 let s2 = String::from("short");
12
// &String viene convertito automaticamente in &str
13 let result = longest(&s1, &s2);
// Stampa "Longest: long string is long"
14 println!("Longest: {}", result);
15
// Un letterale stringa ha il lifetime 'static
16 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

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

Altri esempi Rust di livello 4

← Pratica di digitazione Rust