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