Closed
Description
The following code compiles:
struct Foo;
fn main() {
let mut val = Some(Foo);
while let Some(foo) = val {
if true {
val = None;
} else {
val = None;
}
}
}
If we don't ensure that val
is re-initialized at the end of the loop:
struct Foo;
fn main() {
let mut val = Some(Foo);
while let Some(foo) = val {
if true {
val = None;
} else {
}
}
}
we get the following error:
error[E0382]: use of moved value
--> src/main.rs:5:20
|
5 | while let Some(foo) = val {
| ^^^ value moved here, in previous iteration of loop
|
= note: move occurs because value has type `Foo`, which does not implement the `Copy` trait
help: borrow this field in the pattern to avoid moving `val.0`
|
5 | while let Some(ref foo) = val {
| ^^^
error: aborting due to previous error; 1 warning emitted
This error message seems to imply that the while let pat = variable { ... }
pattern is invalid. However, the fact that val
gets re-initialized in one branch of the loop means that the user likely intended to initialize it in all branches.
We should detect when this kind of case occurs, and explain that val
might not be initialized at the end of the loop. We could even try to detect where the missing initializations need to be inserted, but that might be very difficult.
Metadata
Metadata
Assignees
Labels
Area: The borrow checkerArea: Messages for errors, warnings, and lintsCategory: An issue proposing an enhancement or a PR with one.Diagnostics: An error or lint that doesn't give enough information about the problem at hand.Relevant to the compiler team, which will review and decide on the PR/issue.