Here we look at two kinds of enum that are used everywhere in Rust code. A Result is a special kind of enum that is defined in the standard library. It is used whenever something is executed, that can either end:
- Successfully, then a value Ok (of a certain type T) is returned
- With an error, then an Err value (of type E) is returned
Because this situation is so common, provision is made that the value T and error E types can be as general, or generic, as possible. The Result enum is defined as:
enum Result<T, E> { Ok(T), Err(E) }
An Option is another enum that is defined in the standard library. It is used whenever there is a value, but there can also be a possibility that there is no value. For example, suppose our program expects to read in a value from the console. However, when it runs as a background program by accident, it will never get an input value.
Rust wants to be on the safe side whenever possible, so in this case it is better to read in the value as an Option enum, with two possibilities:
- Some: If there is a value of type T
- None: If there is no value
The value Option again is defined as a generic type:
enum Option<T> { Some(T), None }