Error Handling in Rust
If you are following stack overflow developer survey, you might have seen Rust as most loved programming language 2 years in a row. Rust is probably most fascinating programming language I’ve seen, and I completely agree with survey.
Having said that Learning Rust is not easy, learning curve is very high, and If you are coming from languages like JavaScript like me, it will be very challenging journey but, this tough road is worth it.
If you are very new to learning Rust, I strongly suggest starting with their docs, Rust has one of the best documentations available.
Today we will be looking at error handling in rust.
If you are coming from languages like JavaScript, the way JS and Rust handles errors are poles apart. Enough of talk let’s start with some code 😋😋.
Before coding anything we need to learn Option and Result in Rust.
Option in Rust represents an optional value: every Option is either Some and contains a value, or None, and does not. Option types are very common in Rust code, as they have a number of uses
Result in Rust is the type used for returning and propagating errors. It is an enum with the variants, Ok(T), representing success and containing a value, and Err(E), representing error and containing an error value.
enum Result<T, E> { Ok(T), Err(E),}
Now let’s see some examples.
First we will learn about Option
Now, let’s improve above code little bit
Now let’s see a Generic use case of reading file
I’m still learning Rust, so if you see any mistakes or improvement opportunity let me know in comments.
Hope to you see in Next Rust Article. Peace.