Nick Cameron | 683bcc0 | 2016-05-03 01:01:54 | [diff] [blame] | 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 | |
Scott McMurray | ecde1e1 | 2017-05-07 07:14:04 | [diff] [blame] | 11 | #![feature(try_trait)] |
Nick Cameron | 683bcc0 | 2016-05-03 01:01:54 | [diff] [blame] | 12 | |
Scott McMurray | ecde1e1 | 2017-05-07 07:14:04 | [diff] [blame] | 13 | use std::ops::Try; |
Nick Cameron | 683bcc0 | 2016-05-03 01:01:54 | [diff] [blame] | 14 | |
| 15 | enum MyResult<T, U> { |
| 16 | Awesome(T), |
| 17 | Terrible(U) |
| 18 | } |
| 19 | |
Scott McMurray | ecde1e1 | 2017-05-07 07:14:04 | [diff] [blame] | 20 | impl<U, V> Try for MyResult<U, V> { |
| 21 | type Ok = U; |
Nick Cameron | 683bcc0 | 2016-05-03 01:01:54 | [diff] [blame] | 22 | type Error = V; |
| 23 | |
Scott McMurray | ecde1e1 | 2017-05-07 07:14:04 | [diff] [blame] | 24 | fn from_ok(u: U) -> MyResult<U, V> { |
Nick Cameron | 683bcc0 | 2016-05-03 01:01:54 | [diff] [blame] | 25 | MyResult::Awesome(u) |
| 26 | } |
| 27 | |
| 28 | fn from_error(e: V) -> MyResult<U, V> { |
| 29 | MyResult::Terrible(e) |
| 30 | } |
| 31 | |
Scott McMurray | ecde1e1 | 2017-05-07 07:14:04 | [diff] [blame] | 32 | fn into_result(self) -> Result<U, V> { |
Nick Cameron | 683bcc0 | 2016-05-03 01:01:54 | [diff] [blame] | 33 | match self { |
Scott McMurray | ecde1e1 | 2017-05-07 07:14:04 | [diff] [blame] | 34 | MyResult::Awesome(u) => Ok(u), |
| 35 | MyResult::Terrible(e) => Err(e), |
Nick Cameron | 683bcc0 | 2016-05-03 01:01:54 | [diff] [blame] | 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 | } |