]> git.proxmox.com Git - rustc.git/blame - src/doc/unstable-book/src/library-features/try-trait.md
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / src / doc / unstable-book / src / library-features / try-trait.md
CommitLineData
7cac9316
XL
1# `try_trait`
2
3The tracking issue for this feature is: [#42327]
4
5[#42327]: https://github.com/rust-lang/rust/issues/42327
6
7------------------------
8
9This introduces a new trait `Try` for extending the `?` operator to types
10other than `Result` (a part of [RFC 1859]). The trait provides the canonical
11way to _view_ a type in terms of a success/failure dichotomy. This will
12allow `?` to supplant the `try_opt!` macro on `Option` and the `try_ready!`
13macro on `Poll`, among other things.
14
15[RFC 1859]: https://github.com/rust-lang/rfcs/pull/1859
16
17Here's an example implementation of the trait:
18
6a06907d 19```rust,ignore (cannot-reimpl-Try)
7cac9316
XL
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")]
25pub struct None { _priv: () }
26
27#[unstable(feature = "try_trait", issue = "42327")]
28impl<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
46Note the `Error` associated type here is a new marker. The `?` operator
47allows interconversion between different `Try` implementers only when
48the error type can be converted `Into` the error type of the enclosing
49function (or catch block). Having a distinct error type (as opposed to
50just `()`, or similar) restricts this to where it's semantically meaningful.