]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/std/result.md
New upstream version 1.25.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / std / result.md
1 # `Result`
2
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.
7
8 The `Result<T, E>` enum has two variants:
9
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`)
14
15 ```rust,editable,ignore,mdbook-runnable
16 mod checked {
17 // Mathematical "errors" we want to catch
18 #[derive(Debug)]
19 pub enum MathError {
20 DivisionByZero,
21 NonPositiveLogarithm,
22 NegativeSquareRoot,
23 }
24
25 pub type MathResult = Result<f64, MathError>;
26
27 pub fn div(x: f64, y: f64) -> MathResult {
28 if y == 0.0 {
29 // This operation would `fail`, instead let's return the reason of
30 // the failure wrapped in `Err`
31 Err(MathError::DivisionByZero)
32 } else {
33 // This operation is valid, return the result wrapped in `Ok`
34 Ok(x / y)
35 }
36 }
37
38 pub fn sqrt(x: f64) -> MathResult {
39 if x < 0.0 {
40 Err(MathError::NegativeSquareRoot)
41 } else {
42 Ok(x.sqrt())
43 }
44 }
45
46 pub fn ln(x: f64) -> MathResult {
47 if x <= 0.0 {
48 Err(MathError::NonPositiveLogarithm)
49 } else {
50 Ok(x.ln())
51 }
52 }
53 }
54
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),
64 Ok(sqrt) => sqrt,
65 },
66 },
67 }
68 }
69
70 fn main() {
71 // Will this fail?
72 println!("{}", op(1.0, 10.0));
73 }
74 ```