1
1
# ` ? `
2
2
3
+ <!--
3
4
Chaining results using match can get pretty untidy; luckily, the `?` operator
4
5
can be used to make things pretty again. `?` is used at the end of an expression
5
6
returning a `Result`, and is equivalent to a match expression, where the
6
7
`Err(err)` branch expands to an early `return Err(From::from(err))`, and the `Ok(ok)`
7
8
branch expands to an `ok` expression.
9
+ -->
10
+ マッチを利用して結果をチェインするのは中々面倒です。
11
+ 幸いなことに、` ? ` マクロを使用すればイケてるコードに戻すことができます。
12
+ ` ? ` は` Result ` を返す式の末尾で使います。
13
+ ` Err(err) ` の分岐が` return Err(From::from(err)) ` という早期リターンに展開され、
14
+ ` Ok(ok) ` の分岐が` ok ` の式に展開されるようなマッチ式と等価です。
8
15
9
16
``` rust,editable,ignore,mdbook-runnable
10
17
mod checked {
@@ -42,11 +49,14 @@ mod checked {
42
49
}
43
50
44
51
// Intermediate function
52
+ // 中間関数
45
53
fn op_(x: f64, y: f64) -> MathResult {
46
54
// if `div` "fails", then `DivisionByZero` will be `return`ed
55
+ // `div`が"失敗"したら、`DivisionByZero`が`return`される。
47
56
let ratio = div(x, y)?;
48
57
49
58
// if `ln` "fails", then `NonPositiveLogarithm` will be `return`ed
59
+ // もし`ln`が"失敗"したら、`NonPositiveLogarithm`が`return`される。
50
60
let ln = ln(ratio)?;
51
61
52
62
sqrt(ln)
@@ -72,7 +82,11 @@ fn main() {
72
82
}
73
83
```
74
84
85
+ <!--
75
86
Be sure to check the [documentation][docs],
76
87
as there are many methods to map/compose `Result`.
88
+ -->
89
+ [ 公式ドキュメント] [ docs ] をチェックすることをオススメします。
90
+ ` Result ` 型を扱う関数や` Result ` 型のメソッドが多く挙げられています。
77
91
78
92
[ docs ] : https://doc.rust-lang.org/std/result/index.html
0 commit comments