1 // edition:2021
2
3 // Test that arrays are completely captured by closures by relying on the borrow check diagnostics
4
arrays_1()5 fn arrays_1() {
6 let mut arr = [1, 2, 3, 4, 5];
7
8 let mut c = || {
9 arr[0] += 10;
10 };
11
12 // c will capture `arr` completely, therefore another index into the
13 // array can't be modified here
14 arr[1] += 10;
15 //~^ ERROR: cannot use `arr` because it was mutably borrowed
16 //~| ERROR: cannot use `arr[_]` because it was mutably borrowed
17 c();
18 }
19
arrays_2()20 fn arrays_2() {
21 let mut arr = [1, 2, 3, 4, 5];
22
23 let c = || {
24 println!("{:#?}", &arr[3..4]);
25 };
26
27 // c will capture `arr` completely, therefore another index into the
28 // array can't be modified here
29 arr[1] += 10;
30 //~^ ERROR: cannot assign to `arr[_]` because it is borrowed
31 c();
32 }
33
arrays_3()34 fn arrays_3() {
35 let mut arr = [1, 2, 3, 4, 5];
36
37 let c = || {
38 println!("{}", arr[3]);
39 };
40
41 // c will capture `arr` completely, therefore another index into the
42 // array can't be modified here
43 arr[1] += 10;
44 //~^ ERROR: cannot assign to `arr[_]` because it is borrowed
45 c();
46 }
47
arrays_4()48 fn arrays_4() {
49 let mut arr = [1, 2, 3, 4, 5];
50
51 let mut c = || {
52 arr[1] += 10;
53 };
54
55 // c will capture `arr` completely, therefore we cannot borrow another index
56 // into the array.
57 println!("{}", arr[3]);
58 //~^ ERROR: cannot use `arr` because it was mutably borrowed
59 //~| ERROR: cannot borrow `arr[_]` as immutable because it is also borrowed as mutable
60
61 c();
62 }
63
arrays_5()64 fn arrays_5() {
65 let mut arr = [1, 2, 3, 4, 5];
66
67 let mut c = || {
68 arr[1] += 10;
69 };
70
71 // c will capture `arr` completely, therefore we cannot borrow other indices
72 // into the array.
73 println!("{:#?}", &arr[3..2]);
74 //~^ ERROR: cannot borrow `arr` as immutable because it is also borrowed as mutable
75
76 c();
77 }
78
main()79 fn main() {
80 arrays_1();
81 arrays_2();
82 arrays_3();
83 arrays_4();
84 arrays_5();
85 }
86