Skip to content

Instantly share code, notes, and snippets.

@saiumesh535
Last active March 13, 2019 19:01
Show Gist options
  • Save saiumesh535/15a7f49248a4642ec863bef7eb04f230 to your computer and use it in GitHub Desktop.
Save saiumesh535/15a7f49248a4642ec863bef7eb04f230 to your computer and use it in GitHub Desktop.
Error handling in Rust Option - improved
fn read_from_vec(input: &Vec<i32>, index: usize) -> Result<i32, &'static str> {
return match input.get(index) {
Some(value) => Ok(*value),
None => Err("Out of bound exception")
}
}
fn main() {
// now lets take same example and improve error handling
let numbers = vec![1, 2, 4];
let result = read_from_vec(&numbers, 2);
// now since result is of type **Result** we can handle this in multiple ways
if result.is_ok() {
println!("got the value {}", result.unwrap());
} else {
println!("yo!! got the error {:?}", result.unwrap_err());
}
// above code works but there's an even better way to handle the same
match result {
Ok(data) => println!("indexed value {}", data),
Err(err) => println!("error is {}", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment