]> git.lizzy.rs Git - rust.git/blob - src/libcore/ops/try.rs
Rollup merge of #66941 - CAD97:nord, r=Dylan-DPC
[rust.git] / src / libcore / ops / try.rs
1 /// A trait for customizing the behavior of the `?` operator.
2 ///
3 /// A type implementing `Try` is one that has a canonical way to view it
4 /// in terms of a success/failure dichotomy. This trait allows both
5 /// extracting those success or failure values from an existing instance and
6 /// creating a new instance from a success or failure value.
7 #[unstable(feature = "try_trait", issue = "42327")]
8 #[cfg_attr(not(bootstrap), rustc_on_unimplemented(
9 on(all(
10 any(from_method="from_error", from_method="from_ok"),
11 from_desugaring="QuestionMark"),
12 message="the `?` operator can only be used in {ItemContext} \
13                that returns `Result` or `Option` \
14                (or another type that implements `{Try}`)",
15 label="cannot use the `?` operator in {ItemContext} that returns `{Self}`",
16 enclosing_scope="this function should return `Result` or `Option` to accept `?`"),
17 on(all(from_method="into_result", from_desugaring="QuestionMark"),
18 message="the `?` operator can only be applied to values \
19                that implement `{Try}`",
20 label="the `?` operator cannot be applied to type `{Self}`")
21 ))]
22 #[doc(alias = "?")]
23 pub trait Try {
24     /// The type of this value when viewed as successful.
25     #[unstable(feature = "try_trait", issue = "42327")]
26     type Ok;
27     /// The type of this value when viewed as failed.
28     #[unstable(feature = "try_trait", issue = "42327")]
29     type Error;
30
31     /// Applies the "?" operator. A return of `Ok(t)` means that the
32     /// execution should continue normally, and the result of `?` is the
33     /// value `t`. A return of `Err(e)` means that execution should branch
34     /// to the innermost enclosing `catch`, or return from the function.
35     ///
36     /// If an `Err(e)` result is returned, the value `e` will be "wrapped"
37     /// in the return type of the enclosing scope (which must itself implement
38     /// `Try`). Specifically, the value `X::from_error(From::from(e))`
39     /// is returned, where `X` is the return type of the enclosing function.
40     #[unstable(feature = "try_trait", issue = "42327")]
41     fn into_result(self) -> Result<Self::Ok, Self::Error>;
42
43     /// Wrap an error value to construct the composite result. For example,
44     /// `Result::Err(x)` and `Result::from_error(x)` are equivalent.
45     #[unstable(feature = "try_trait", issue = "42327")]
46     fn from_error(v: Self::Error) -> Self;
47
48     /// Wrap an OK value to construct the composite result. For example,
49     /// `Result::Ok(x)` and `Result::from_ok(x)` are equivalent.
50     #[unstable(feature = "try_trait", issue = "42327")]
51     fn from_ok(v: Self::Ok) -> Self;
52 }