Provide more general note for borrowing outside of closure

This commit is contained in:
yukang 2025-11-06 08:48:09 +08:00
parent c0ff72ffc4
commit 883b2dc420
3 changed files with 38 additions and 0 deletions

View file

@ -690,6 +690,17 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
);
diag.span_label(*span, format!("`{fr_name}` escapes the {escapes_from} body here"));
} else {
diag.span_label(
*span,
format!("a temporary borrow escapes the {escapes_from} body here"),
);
if let Some((Some(outlived_name), _)) = outlived_fr_name_and_span {
diag.help(format!(
"`{outlived_name}` is declared outside the {escapes_from}, \
so any data borrowed inside the {escapes_from} cannot be stored into it"
));
}
}
// Only show an extra note if we can find an 'error region' for both of the region

View file

@ -0,0 +1,13 @@
// Test for issue #148392
// Provides helpful explanations even for anonymous references
// under the scenario of escaping closure
#![allow(unused)]
fn main() {
let a = 0;
let mut b = None;
move || {
b = Some(&a); //~ ERROR borrowed data escapes outside of closure
};
}

View file

@ -0,0 +1,14 @@
error[E0521]: borrowed data escapes outside of closure
--> $DIR/borrowed-data-escapes-closure-148392.rs:11:9
|
LL | let mut b = None;
| ----- `b` declared here, outside of the closure body
LL | move || {
LL | b = Some(&a);
| ^^^^^^^^^^^^ a temporary borrow escapes the closure body here
|
= help: `b` is declared outside the closure, so any data borrowed inside the closure cannot be stored into it
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0521`.