Skip to content

Suggest .as_ref() on E0382 when possible #84165

Closed
@estebank

Description

@estebank

Given the following code:

struct Struct;
fn bar(s: &Struct) -> Struct {
    Struct
}

fn main() {
    let foo = Some(Struct);
    let _x: Option<Struct> = foo
        .map(|s| bar(&s));
    let _y = foo;
}

The current output is:

error[E0382]: use of moved value: `foo`
   --> src/main.rs:10:14
    |
7   |     let foo = Some(Struct);
    |         --- move occurs because `foo` has type `Option<Struct>`, which does not implement the `Copy` trait
8   |     let _x: Option<Struct> = foo
9   |         .map(|s| bar(&s));
    |          ---------------- `foo` moved due to this method call
10  |     let _y = foo;
    |              ^^^ value used here after move

We should suggest calling .as_ref() before the .map(...), as we do in some type errors.

error[E0308]: mismatched types
  --> src/main.rs:10:22
   |
10 |         .map(|s| bar(s));
   |          ---         ^ expected `&Struct`, found struct `Struct`
   |          |
   |          help: consider using `as_ref` instead: `as_ref().map`

This has been seen to cause trouble in the wild https://news.ycombinator.com/item?id=26794551

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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