]> git.lizzy.rs Git - rust.git/blob - src/test/ui/try-operator-custom.rs
Auto merge of #61937 - AaronKutch:master, r=scottmcm
[rust.git] / src / test / ui / try-operator-custom.rs
1 // run-pass
2
3 #![feature(try_trait)]
4
5 use std::ops::Try;
6
7 enum MyResult<T, U> {
8     Awesome(T),
9     Terrible(U)
10 }
11
12 impl<U, V> Try for MyResult<U, V> {
13     type Ok = U;
14     type Error = V;
15
16     fn from_ok(u: U) -> MyResult<U, V> {
17         MyResult::Awesome(u)
18     }
19
20     fn from_error(e: V) -> MyResult<U, V> {
21         MyResult::Terrible(e)
22     }
23
24     fn into_result(self) -> Result<U, V> {
25         match self {
26             MyResult::Awesome(u) => Ok(u),
27             MyResult::Terrible(e) => Err(e),
28         }
29     }
30 }
31
32 fn f(x: i32) -> Result<i32, String> {
33     if x == 0 {
34         Ok(42)
35     } else {
36         let y = g(x)?;
37         Ok(y)
38     }
39 }
40
41 fn g(x: i32) -> MyResult<i32, String> {
42     let _y = f(x - 1)?;
43     MyResult::Terrible("Hello".to_owned())
44 }
45
46 fn h() -> MyResult<i32, String> {
47     let a: Result<i32, &'static str> = Err("Hello");
48     let b = a?;
49     MyResult::Awesome(b)
50 }
51
52 fn i() -> MyResult<i32, String> {
53     let a: MyResult<i32, &'static str> = MyResult::Terrible("Hello");
54     let b = a?;
55     MyResult::Awesome(b)
56 }
57
58 fn main() {
59     assert!(f(0) == Ok(42));
60     assert!(f(10) == Err("Hello".to_owned()));
61     let _ = h();
62     let _ = i();
63 }