blob: 82ba70c9459448832e45bdf8b1bd23df02edb958 [file] [log] [blame]
Nick Cameron683bcc02016-05-03 01:01:541// 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 McMurrayecde1e12017-05-07 07:14:0411#![feature(try_trait)]
Nick Cameron683bcc02016-05-03 01:01:5412
Scott McMurrayecde1e12017-05-07 07:14:0413use std::ops::Try;
Nick Cameron683bcc02016-05-03 01:01:5414
15enum MyResult<T, U> {
16 Awesome(T),
17 Terrible(U)
18}
19
Scott McMurrayecde1e12017-05-07 07:14:0420impl<U, V> Try for MyResult<U, V> {
21 type Ok = U;
Nick Cameron683bcc02016-05-03 01:01:5422 type Error = V;
23
Scott McMurrayecde1e12017-05-07 07:14:0424 fn from_ok(u: U) -> MyResult<U, V> {
Nick Cameron683bcc02016-05-03 01:01:5425 MyResult::Awesome(u)
26 }
27
28 fn from_error(e: V) -> MyResult<U, V> {
29 MyResult::Terrible(e)
30 }
31
Scott McMurrayecde1e12017-05-07 07:14:0432 fn into_result(self) -> Result<U, V> {
Nick Cameron683bcc02016-05-03 01:01:5433 match self {
Scott McMurrayecde1e12017-05-07 07:14:0434 MyResult::Awesome(u) => Ok(u),
35 MyResult::Terrible(e) => Err(e),
Nick Cameron683bcc02016-05-03 01:01:5436 }
37 }
38}
39
40fn 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
49fn g(x: i32) -> MyResult<i32, String> {
50 let _y = f(x - 1)?;
51 MyResult::Terrible("Hello".to_owned())
52}
53
54fn h() -> MyResult<i32, String> {
55 let a: Result<i32, &'static str> = Err("Hello");
56 let b = a?;
57 MyResult::Awesome(b)
58}
59
60fn i() -> MyResult<i32, String> {
61 let a: MyResult<i32, &'static str> = MyResult::Terrible("Hello");
62 let b = a?;
63 MyResult::Awesome(b)
64}
65
66fn main() {
67 assert!(f(0) == Ok(42));
68 assert!(f(10) == Err("Hello".to_owned()));
69 let _ = h();
70 let _ = i();
71}