]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/try-block.rs
Auto merge of #53815 - F001:if-let-guard, r=petrochenkov
[rust.git] / src / test / run-pass / try-block.rs
1 // Copyright 2017 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 // compile-flags: --edition 2018
12
13 #![feature(try_blocks)]
14
15 struct catch {}
16
17 pub fn main() {
18     let catch_result: Option<_> = try {
19         let x = 5;
20         x
21     };
22     assert_eq!(catch_result, Some(5));
23
24     let mut catch = true;
25     while catch { catch = false; }
26     assert_eq!(catch, false);
27
28     catch = if catch { false } else { true };
29     assert_eq!(catch, true);
30
31     match catch {
32         _ => {}
33     };
34
35     let catch_err: Result<_, i32> = try {
36         Err(22)?;
37         1
38     };
39     assert_eq!(catch_err, Err(22));
40
41     let catch_okay: Result<i32, i32> = try {
42         if false { Err(25)?; }
43         Ok::<(), i32>(())?;
44         28
45     };
46     assert_eq!(catch_okay, Ok(28));
47
48     let catch_from_loop: Result<i32, i32> = try {
49         for i in 0..10 {
50             if i < 5 { Ok::<i32, i32>(i)?; } else { Err(i)?; }
51         }
52         22
53     };
54     assert_eq!(catch_from_loop, Err(5));
55
56     let cfg_init;
57     let _res: Result<(), ()> = try {
58         cfg_init = 5;
59     };
60     assert_eq!(cfg_init, 5);
61
62     let cfg_init_2;
63     let _res: Result<(), ()> = try {
64         cfg_init_2 = 6;
65         Err(())?;
66     };
67     assert_eq!(cfg_init_2, 6);
68
69     let my_string = "test".to_string();
70     let res: Result<&str, ()> = try {
71         // Unfortunately, deref doesn't fire here (#49356)
72         &my_string[..]
73     };
74     assert_eq!(res, Ok("test"));
75
76     let my_opt: Option<_> = try { () };
77     assert_eq!(my_opt, Some(()));
78
79     let my_opt: Option<_> = try { };
80     assert_eq!(my_opt, Some(()));
81 }