Operatore ? in Rust
Livello 4312 battiture
L'operatore ? propaga gli errori presto, restituendo Err se l'operazione fallisce.
Codice Rust
// Restituisce il numero raddoppiato oppure l'errore di parsing1fn parse_and_double(s: &str) -> Result<i32, std::num::ParseIntError> { // Se parse() fallisce, ? restituisce subito quell'Err dalla funzione2 let n: i32 = s.parse()?; // Si arriva qui solo se il parsing è riuscito3 Ok(n * 2)4}5 // Punto di ingresso del programma6fn main() { // Input da provare: "abc" non è un numero7 let results = vec!["10", "abc", "42"];8 // Elabora ogni input in ordine9 for s in results { // Controlla se la chiamata è riuscita10 match parse_and_double(s) { // "10" → "10 doubled is 20", "42" → "42 doubled is 84"11 Ok(n) => println!("{} doubled is {}", s, n), // "abc": e viene stampato come "invalid digit found in string"12 Err(e) => println!("Failed to parse '{}': {}", s, e),13 }14 }15}Output
10 doubled is 20 Failed to parse 'abc': invalid digit found in string 42 doubled is 84
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.
"× 10,× 9(× 9)× 9{× 8}× 8:× 7_× 4=× 4>× 4