3 We've seen that the `Option` enum can be used as a return value from functions
4 that may fail, where `None` can be returned to indicate failure. However,
5 sometimes it is important to express *why* an operation failed. To do this we
6 have the `Result` enum.
8 The `Result<T, E>` enum has two variants:
10 * `Ok(value)` which indicates that the operation succeeded, and wraps the
11 `value` returned by the operation. (`value` has type `T`)
12 * `Err(why)`, which indicates that the operation failed, and wraps `why`,
13 which (hopefully) explains the cause of the failure. (`why` has type `E`)
15 ```rust,editable,ignore,mdbook-runnable
17 // Mathematical "errors" we want to catch
25 pub type MathResult = Result<f64, MathError>;
27 pub fn div(x: f64, y: f64) -> MathResult {
29 // This operation would `fail`, instead let's return the reason of
30 // the failure wrapped in `Err`
31 Err(MathError::DivisionByZero)
33 // This operation is valid, return the result wrapped in `Ok`
38 pub fn sqrt(x: f64) -> MathResult {
40 Err(MathError::NegativeSquareRoot)
46 pub fn ln(x: f64) -> MathResult {
48 Err(MathError::NonPositiveLogarithm)
55 // `op(x, y)` === `sqrt(ln(x / y))`
56 fn op(x: f64, y: f64) -> f64 {
57 // This is a three level match pyramid!
58 match checked::div(x, y) {
59 Err(why) => panic!("{:?}", why),
60 Ok(ratio) => match checked::ln(ratio) {
61 Err(why) => panic!("{:?}", why),
62 Ok(ln) => match checked::sqrt(ln) {
63 Err(why) => panic!("{:?}", why),
72 println!("{}", op(1.0, 10.0));