Skip to content

Instantly share code, notes, and snippets.

@saiumesh535
Last active March 13, 2019 18:27
Show Gist options
  • Save saiumesh535/beeff32aeddb46ca92d902aa0a00e824 to your computer and use it in GitHub Desktop.
Save saiumesh535/beeff32aeddb46ca92d902aa0a00e824 to your computer and use it in GitHub Desktop.
Error handling in Rust Options
fn main() {
// first let's define vector/array of numbers
let numbers = vec![1, 2, 4];
// now let's try to read value from vector
let index_one = numbers[1];
println!("value at index {}", index_one);
// now let's try to read 10th index which doesn't exists
// since Rust doesn't have neither null nor try/catch to handle error
// so we will take leverage of **Option**
// un comment below two line to check error
// let out_of_index = numbers[10];
// println!("this will throw error {}", out_of_index);
// above code would result in following error
// thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 10'
// rust has very interesting way to handle these errors
// we will take advantage of Option and get method from
// vector to handle these kind of errors
// get method of vector returns **Option** enum
// Option will have two properties Some and None
// let's see how to read/catch error
match numbers.get(10) {
Some(value) => println!("Hello {}", value),
None => println!("Yo!! out of bound error")
}
// now let's see how to read value from it
let result = match numbers.get(10) {
Some(value) => value,
None => &-1 // defaulting to -1
};
println!("result is {}", result);
// as you can see above code works well but,
// we can improve code by taking advantage of Result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment