Error Handling
Error handling in Rust is very different from Perl. Rust has no null value like Perl's undef
. Rust doesn't really have exceptions either, though we can panic!
which terminates safely and unwinds the stack. Instead, Rust leverages its type system to create two very common enumerations: Option
and Result
.
Option
An option is either Some
, and has some data, or it is None
, and has no data.
#![allow(unused_variables)] fn main() { pub enum Option<T> { Some(T), None, } }
Since we can have all sorts of optional types, we use a generic type T. An option is either type Some(T)
, in which case our data is of type T, or it is type None
and there is no data.
Result
A result is either Ok
, and has some good data, or it is Err
, and has some error data.
#![allow(unused_variables)] fn main() { pub enum Result<T, E> { Ok(T), Err(E), } }
Now there are two generic types, good data of type T and error data of type E.