Skip to content

Wrong error message about uninitialized variable in loop #72649

Closed
@m-ou-se

Description

@m-ou-se

Forgetting to initialize a non-Copy variable in a loop and then referring to it gives a 'borrowed after move' error, instead of a 'possibly-uninitialized variable' error:

fn bla(_: &mut String) {}

fn main() {
    for _ in 0..10 {
        let mut x: String;
        bla(&mut x);
    }
}
error[E0382]: borrow of moved value: `x`
 --> src/main.rs:6:13
  |
5 |         let mut x: String;
  |             ----- move occurs because `x` has type `std::string::String`, which does not implement the `Copy` trait
6 |         bla(&mut x);
  |             ^^^^^^ value borrowed here after move
7 |     }
  |     - value moved here, in previous iteration of loop

Using a Copy type like i32 does result in the right error:

error[E0381]: borrow of possibly-uninitialized variable: `x`
 --> src/main.rs:6:13
  |
6 |         bla(&mut x);
  |             ^^^^^^ use of possibly-uninitialized `x`

Tested with 1.43.0 (stable) and 1.45.0-nightly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.D-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.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