@@ -5,3 +5,46 @@ The tracking issue for this feature is: [#42327]
5
5
[ #42327 ] : https://github.com/rust-lang/rust/issues/42327
6
6
7
7
------------------------
8
+
9
+ This introduces a new trait ` Try ` for extending the ` ? ` operator to types
10
+ other than ` Result ` (a part of [ RFC 1859] ). The trait provides the canonical
11
+ way to _ view_ a type in terms of a success/failure dichotomy. This will
12
+ allow ` ? ` to supplant the ` try_opt! ` macro on ` Option ` and the ` try_ready! `
13
+ macro on ` Poll ` , among other things.
14
+
15
+ [ RFC 1859 ] : https://github.com/rust-lang/rfcs/pull/1859
16
+
17
+ Here's an example implementation of the trait:
18
+
19
+ ``` rust,ignore
20
+ /// A distinct type to represent the `None` value of an `Option`.
21
+ ///
22
+ /// This enables using the `?` operator on `Option`; it's rarely useful alone.
23
+ #[derive(Debug)]
24
+ #[unstable(feature = "try_trait", issue = "42327")]
25
+ pub struct None { _priv: () }
26
+
27
+ #[unstable(feature = "try_trait", issue = "42327")]
28
+ impl<T> ops::Try for Option<T> {
29
+ type Ok = T;
30
+ type Error = None;
31
+
32
+ fn into_result(self) -> Result<T, None> {
33
+ self.ok_or(None { _priv: () })
34
+ }
35
+
36
+ fn from_ok(v: T) -> Self {
37
+ Some(v)
38
+ }
39
+
40
+ fn from_error(_: None) -> Self {
41
+ None
42
+ }
43
+ }
44
+ ```
45
+
46
+ Note the ` Error ` associated type here is a new marker. The ` ? ` operator
47
+ allows interconversion between different ` Try ` implementers only when
48
+ the error type can be converted ` Into ` the error type of the enclosing
49
+ function (or catch block). Having a distinct error type (as opposed to
50
+ just ` () ` , or similar) restricts this to where it's semantically meaningful.
0 commit comments