]> git.lizzy.rs Git - rust.git/blob - tests/ui/borrowck/borrow-immutable-upvar-mutation.rs
Rollup merge of #106726 - cmorin6:fix-comment-typos, r=Nilstrieb
[rust.git] / tests / ui / borrowck / borrow-immutable-upvar-mutation.rs
1 #![feature(unboxed_closures, tuple_trait)]
2
3 // Tests that we can't assign to or mutably borrow upvars from `Fn`
4 // closures (issue #17780)
5
6 fn set(x: &mut usize) {
7     *x = 5;
8 }
9
10 fn to_fn<A: std::marker::Tuple, F: Fn<A>>(f: F) -> F {
11     f
12 }
13 fn to_fn_mut<A: std::marker::Tuple, F: FnMut<A>>(f: F) -> F {
14     f
15 }
16
17 fn main() {
18     // By-ref captures
19     {
20         let mut x = 0;
21         let _f = to_fn(|| x = 42); //~ ERROR cannot assign
22
23         let mut y = 0;
24         let _g = to_fn(|| set(&mut y)); //~ ERROR cannot borrow
25
26         let mut z = 0;
27         let _h = to_fn_mut(|| {
28             set(&mut z);
29             to_fn(|| z = 42); //~ ERROR cannot assign
30         });
31     }
32
33     // By-value captures
34     {
35         let mut x = 0;
36         let _f = to_fn(move || x = 42); //~ ERROR cannot assign
37
38         let mut y = 0;
39         let _g = to_fn(move || set(&mut y)); //~ ERROR cannot borrow
40
41         let mut z = 0;
42         let _h = to_fn_mut(move || {
43             set(&mut z);
44             to_fn(move || z = 42);
45             //~^ ERROR cannot assign
46         });
47     }
48 }
49
50 fn foo() -> Box<dyn Fn() -> usize> {
51     let mut x = 0;
52     Box::new(move || {
53         x += 1; //~ ERROR cannot assign
54         x
55     })
56 }