Skip to content

Misleading error message when variable is not re-initialized in loop #83760

Closed
@Aaron1011

Description

@Aaron1011

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

A-borrow-checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions