]> git.lizzy.rs Git - rust.git/blob - src/test/ui/try-block/try-block-bad-lifetime.rs
Rollup merge of #53592 - matthiaskrgr:str_doc, r=alexcrichton
[rust.git] / src / test / ui / try-block / try-block-bad-lifetime.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 #![inline(never)]
16 fn do_something_with<T>(_x: T) {}
17
18 // This test checks that borrows made and returned inside try blocks are properly constrained
19 pub fn main() {
20     {
21         // Test that borrows returned from a try block must be valid for the lifetime of the
22         // result variable
23         let result: Result<(), &str> = try {
24             let my_string = String::from("");
25             let my_str: & str = & my_string;
26             //~^ ERROR `my_string` does not live long enough
27             Err(my_str) ?;
28             Err("") ?;
29         };
30         do_something_with(result);
31     }
32
33     {
34         // Test that borrows returned from try blocks freeze their referent
35         let mut i = 5;
36         let k = &mut i;
37         let mut j: Result<(), &mut i32> = try {
38             Err(k) ?;
39             i = 10; //~ ERROR cannot assign to `i` because it is borrowed
40         };
41         ::std::mem::drop(k); //~ ERROR use of moved value: `k`
42         i = 40; //~ ERROR cannot assign to `i` because it is borrowed
43
44         let i_ptr = if let Err(i_ptr) = j { i_ptr } else { panic ! ("") };
45         *i_ptr = 50;
46     }
47 }
48