Skip to content

Wrong error message with closures when variable moved #63405

Closed
@shengsheng

Description

@shengsheng

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=c4b92f189e40cc2a6e8a6d13a24e4ee8

struct T(u32);

fn by_value(_: T) {}
fn by_ref(_: &T) {}
    
fn main() {
    let z = T(123);
    
    let closure = || {
        by_ref(&z);
        by_value(z);
    };
    
    closure();
    
    by_value(z);
}

Output:

   Compiling playground v0.0.1 (/playground)
error[E0382]: use of moved value: `z`
  --> src/main.rs:16:14
   |
7  |     let z = T(123);
   |         - move occurs because `z` has type `T`, which does not implement the `Copy` trait
8  |     
9  |     let closure = || {
   |                   -- value moved into closure here
10 |         by_ref(&z);
   |                 - variable moved due to use in closure
...
16 |     by_value(z);
   |              ^ value used here after move

error: aborting due to previous error

For more information about this error, try `rustc --explain E0382`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

The move actually happen in line 11: by_value(z); not line 10.

Expect output:

11 |         by_value(z);
   |                  - variable moved due to use in closure

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.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