Skip to content

Commit aa58439

Browse files
committed
Fail gracefully if mutating on a use closure and the closure it not declared mut
1 parent 6eb6ff6 commit aa58439

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -823,7 +823,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
823823
) => {
824824
capture_reason = format!("mutable borrow of `{upvar}`");
825825
}
826-
ty::UpvarCapture::ByValue => {
826+
ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {
827827
capture_reason = format!("possible mutation of `{upvar}`");
828828
}
829829
_ => bug!("upvar `{upvar}` borrowed, but not mutably"),
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#![feature(ergonomic_clones)]
2+
3+
fn main() {
4+
let mut my_var = false;
5+
let callback = use || {
6+
my_var = true;
7+
};
8+
callback();
9+
//~^ ERROR cannot borrow `callback` as mutable, as it is not declared as mutable [E0596]
10+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
error[E0596]: cannot borrow `callback` as mutable, as it is not declared as mutable
2+
--> $DIR/mutation2.rs:8:5
3+
|
4+
LL | my_var = true;
5+
| ------ calling `callback` requires mutable binding due to possible mutation of `my_var`
6+
LL | };
7+
LL | callback();
8+
| ^^^^^^^^ cannot borrow as mutable
9+
|
10+
help: consider changing this to be mutable
11+
|
12+
LL | let mut callback = use || {
13+
| +++
14+
15+
error: aborting due to 1 previous error
16+
17+
For more information about this error, try `rustc --explain E0596`.

0 commit comments

Comments
 (0)