Rust errors
From wikinotes
Rust has two primary methods of handling errors.
panic!()
halts/exits the programResult
types are for handle-able errors
panic
- intended for halting application, not control flow
- have backtraces
panic!("tried to X but couldn't Y") // convert panic to result // (not intended for native rust code) let result = panic::catch_unwind(|| { panic!("oh no!"); });
Result
The result type is an enum, whose options
Ok, Err
have been merged into the global scope throughprelude
.Example.
fn is_one(i: isize) -> Result<String, String> { if i == 1 { Ok("success".to_string()) } else { Err("not success".to_string()) } } fn main() { let result = match is_one(2) { Ok(x) => format!("horay: {}", x), Err(x) => format!("[ERROR] {}", x), }; println!("{}", result); }