]> git.lizzy.rs Git - rust.git/blob - src/libcore/ops/try.rs
Rollup merge of #58595 - stjepang:make-duration-consts-associated, r=oli-obk
[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 #[rustc_on_unimplemented(
9    on(all(
10        any(from_method="from_error", from_method="from_ok"),
11        from_desugaring="?"),
12       message="the `?` operator can only be used in a \
13                function that returns `Result` or `Option` \
14                (or another type that implements `{Try}`)",
15       label="cannot use the `?` operator in a function that returns `{Self}`"),
16    on(all(from_method="into_result", from_desugaring="?"),
17       message="the `?` operator can only be applied to values \
18                that implement `{Try}`",
19       label="the `?` operator cannot be applied to type `{Self}`")
20 )]
21 #[doc(alias = "?")]
22 pub trait Try {
23     /// The type of this value when viewed as successful.
24     #[unstable(feature = "try_trait", issue = "42327")]
25     type Ok;
26     /// The type of this value when viewed as failed.
27     #[unstable(feature = "try_trait", issue = "42327")]
28     type Error;
29
30     /// Applies the "?" operator. A return of `Ok(t)` means that the
31     /// execution should continue normally, and the result of `?` is the
32     /// value `t`. A return of `Err(e)` means that execution should branch
33     /// to the innermost enclosing `catch`, or return from the function.
34     ///
35     /// If an `Err(e)` result is returned, the value `e` will be "wrapped"
36     /// in the return type of the enclosing scope (which must itself implement
37     /// `Try`). Specifically, the value `X::from_error(From::from(e))`
38     /// is returned, where `X` is the return type of the enclosing function.
39     #[unstable(feature = "try_trait", issue = "42327")]
40     fn into_result(self) -> Result<Self::Ok, Self::Error>;
41
42     /// Wrap an error value to construct the composite result. For example,
43     /// `Result::Err(x)` and `Result::from_error(x)` are equivalent.
44     #[unstable(feature = "try_trait", issue = "42327")]
45     fn from_error(v: Self::Error) -> Self;
46
47     /// Wrap an OK value to construct the composite result. For example,
48     /// `Result::Ok(x)` and `Result::from_ok(x)` are equivalent.
49     #[unstable(feature = "try_trait", issue = "42327")]
50     fn from_ok(v: Self::Ok) -> Self;
51 }