Skip to content

Commit c775927

Browse files
committed
Suggest borrowing Vec<NonCopy> in for loop
Partially address #64167.
1 parent 7da653f commit c775927

File tree

4 files changed

+53
-0
lines changed

4 files changed

+53
-0
lines changed

src/librustc_mir/borrow_check/diagnostics/move_errors.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use rustc::mir::*;
22
use rustc::ty;
33
use rustc_errors::{Applicability, DiagnosticBuilder};
4+
use rustc_span::source_map::DesugaringKind;
45
use rustc_span::Span;
56

67
use crate::borrow_check::diagnostics::UseSpans;
@@ -397,6 +398,16 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
397398
format!("{}.as_ref()", snippet),
398399
Applicability::MaybeIncorrect,
399400
);
401+
} else if span.is_desugaring(DesugaringKind::ForLoop)
402+
&& move_ty.starts_with("std::vec::Vec")
403+
{
404+
// FIXME: suggest for anything that implements `IntoIterator`.
405+
err.span_suggestion(
406+
span,
407+
"consider iterating over a slice of the `Vec`'s content",
408+
format!("&{}", snippet),
409+
Applicability::MaybeIncorrect,
410+
);
400411
}
401412
}
402413
err
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// run-rustfix
2+
#![allow(dead_code)]
3+
4+
struct Foo {
5+
v: Vec<u32>,
6+
}
7+
8+
impl Foo {
9+
fn bar(&self) {
10+
for _ in &self.v { //~ ERROR cannot move out of `self.v` which is behind a shared reference
11+
}
12+
}
13+
}
14+
15+
fn main() {}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// run-rustfix
2+
#![allow(dead_code)]
3+
4+
struct Foo {
5+
v: Vec<u32>,
6+
}
7+
8+
impl Foo {
9+
fn bar(&self) {
10+
for _ in self.v { //~ ERROR cannot move out of `self.v` which is behind a shared reference
11+
}
12+
}
13+
}
14+
15+
fn main() {}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
error[E0507]: cannot move out of `self.v` which is behind a shared reference
2+
--> $DIR/for-i-in-vec.rs:10:18
3+
|
4+
LL | for _ in self.v {
5+
| ^^^^^^
6+
| |
7+
| move occurs because `self.v` has type `std::vec::Vec<u32>`, which does not implement the `Copy` trait
8+
| help: consider iterating over a slice of the `Vec`'s content: `&self.v`
9+
10+
error: aborting due to previous error
11+
12+
For more information about this error, try `rustc --explain E0507`.

0 commit comments

Comments
 (0)