Gestione degli errori con Result in Rust
Livello 3168 battiture
Result<T, E> viene restituito dalle operazioni che possono fallire: Ok contiene il valore di successo ed Err l'errore. Qui il tipo di errore è una String posseduta.
Codice Rust
// Il successo porta un i32, il fallimento un messaggio String1fn divide(a: i32, b: i32) -> Result<i32, String> { // Restituisce Err con una String se b == 0, altrimenti Ok con il quoziente // to_string() trasforma il letterale &str nella String posseduta richiesta dal tipo2 if b == 0 { Err("division by zero".to_string()) } else { Ok(a / b) }3}// 10 / 2 riesce, quindi {:?} stampa Ok(5)4fn main() { println!("{:?}", divide(10, 2)); }Output
Ok(5)
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.
(× 7)× 7{× 5}× 5,× 4"× 4:× 3=× 2>× 2_× 1