]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/try-operator-custom.rs
Lower `?` to `Try` instead of `Carrier`
[rust.git] / src / test / run-pass / try-operator-custom.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![feature(try_trait)]
12
13 use std::ops::Try;
14
15 enum MyResult<T, U> {
16     Awesome(T),
17     Terrible(U)
18 }
19
20 impl<U, V> Try for MyResult<U, V> {
21     type Ok = U;
22     type Error = V;
23
24     fn from_ok(u: U) -> MyResult<U, V> {
25         MyResult::Awesome(u)
26     }
27
28     fn from_error(e: V) -> MyResult<U, V> {
29         MyResult::Terrible(e)
30     }
31
32     fn into_result(self) -> Result<U, V> {
33         match self {
34             MyResult::Awesome(u) => Ok(u),
35             MyResult::Terrible(e) => Err(e),
36         }
37     }
38 }
39
40 fn f(x: i32) -> Result<i32, String> {
41     if x == 0 {
42         Ok(42)
43     } else {
44         let y = g(x)?;
45         Ok(y)
46     }
47 }
48
49 fn g(x: i32) -> MyResult<i32, String> {
50     let _y = f(x - 1)?;
51     MyResult::Terrible("Hello".to_owned())
52 }
53
54 fn h() -> MyResult<i32, String> {
55     let a: Result<i32, &'static str> = Err("Hello");
56     let b = a?;
57     MyResult::Awesome(b)
58 }
59
60 fn i() -> MyResult<i32, String> {
61     let a: MyResult<i32, &'static str> = MyResult::Terrible("Hello");
62     let b = a?;
63     MyResult::Awesome(b)
64 }
65
66 fn main() {
67     assert!(f(0) == Ok(42));
68     assert!(f(10) == Err("Hello".to_owned()));
69     let _ = h();
70     let _ = i();
71 }