Rust Error Handling
Handling errors with Result and Option
Result Type
enum Result<T, E> { # built-in enum
Ok(T), # success with value
Err(E), # error with value
}
Using Result
use std::fs::File;
let f = File::open("file.txt"); # returns Result
match f {
Ok(file) => println!("Success"),
Err(error) => println!("Error: {}"{}, error),
}
Unwrap and Expect
let f = File::open("file.txt").unwrap(); # panic on error
let f = File::open("file.txt").expect("Failed to open"); # custom panic message
Question Mark Operator
fn read_file() -> Result<String, std::io::Error> {
let mut f = File::open("file.txt")?; # return error if Err
let mut contents = String::new();
f.read_to_string(&mut contents)?;
Ok(contents) # return Ok variant
}
Option Type
let some = Some(5); # has value
let none: Option<i32> = None; # no value
let x = some.unwrap_or(0); # use default if None