Skip to content

Error E0507 suggestion is invalid with let else statements #104838

Closed

Description

Given the following code (playground):

struct Testing {
    a: Option<String>
}

fn testing(a: &Testing) {
    let Some(_s) = a.a else {
        return;
    };
}

The current output is:

error[[E0507]](https://doc.rust-lang.org/nightly/error-index.html#E0507): cannot move out of `a.a` as enum variant `Some` which is behind a shared reference
 --> src/lib.rs:6:14
  |
6 |     let Some(_s) = a.a else {
  |              ^^
  |              |
  |              move occurs because `a.a.0` has type `String`, which does not implement the `Copy` trait
  |              help: consider borrowing here: `&_s`

For more information about this error, try `rustc --explain E0507`.
error: could not compile `playground` due to previous error

Ideally the output should look like:

error[[E0507]](https://doc.rust-lang.org/nightly/error-index.html#E0507): cannot move out of `a.a` as enum variant `Some` which is behind a shared reference
 --> src/lib.rs:6:14
  |
6 |     let Some(_s) = a.a else {
  |              ^^    ^^^
  |              |     |
  |              |     help: consider borrowing here: `&a.a`       
  |              |
  |              move occurs because `a.a.0` has type `String`, which does not implement the `Copy` trait


For more information about this error, try `rustc --explain E0507`.
error: could not compile `playground` due to previous error

An alternative would be to recommend using ref, but this would not be consistent with the match suggestion:

fn testing2(a: &Testing) {
    match a.a {
        Some(_s) => return,
        None => {}
    }
}
error[[E0507]](https://doc.rust-lang.org/nightly/error-index.html#E0507): cannot move out of `a.a` as enum variant `Some` which is behind a shared reference
  --> src/lib.rs:12:11
   |
12 |     match a.a {
   |           ^^^ help: consider borrowing here: `&a.a`
13 |         Some(_s) => return,
   |              --
   |              |
   |              data moved here
   |              move occurs because `_s` has type `String`, which does not implement the `Copy` trait

Tested with Nightly version: 1.67.0-nightly (2022-11-23 70f8737)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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