Last active
March 13, 2019 19:01
-
-
Save saiumesh535/15a7f49248a4642ec863bef7eb04f230 to your computer and use it in GitHub Desktop.
Error handling in Rust Option - improved
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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