Destrutturazione con pattern matching in Rust

Livello 4314 battiture

Il pattern matching può destrutturare struct e associare campi a variabili, permettendo logica condizionale espressiva.

Codice Rust

// struct Point definisce un punto con coordinate x e y
1struct Point { x: i32, y: i32 }
// fn describe prende un Point e stampa una descrizione
2fn describe(p: Point) {
// match p destruttura il Point
3 match p {
// Point { x: 0, y: 0 } corrisponde solo quando entrambi sono 0
4 Point { x: 0, y: 0 } => println!("Origin"),
// Point { x, y: 0 } corrisponde quando y è 0, associa x
5 Point { x, y: 0 } => println!("On x-axis at {}", x),
// Point { x: 0, y } corrisponde quando x è 0, associa y
6 Point { x: 0, y } => println!("On y-axis at {}", y),
// Point { x, y } cattura tutti gli altri casi, associa entrambi
7 Point { x, y } => println!("At ({}, {})", x, y),
8 }
9}
// fn main() è il punto di ingresso
// Chiama describe con un Point sull'asse x
10fn main() { describe(Point { x: 5, y: 0 }); }

Output

On x-axis at 5
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.

  • ,× 15
  • {× 13
  • }× 13
  • :× 9
  • "× 8
  • (× 8
  • )× 8
  • !× 4
  • =× 4
  • >× 4

Altri esempi Rust di livello 4

← Pratica di digitazione Rust