Skip to content

Error message suggests using & and mut when matching on fields behind a &mut, rather than &mut or ref mut #74617

Open
@L-F-Stack-Exchange

Description

@L-F-Stack-Exchange

When compiling this code, which attempts to match a field behind a mutable reference against a moving pattern:

struct S {
    field: Option<String>,
}

fn f(arg: &mut S) {
    match arg.field {
        Some(s) => s.push('a'),
        None => {}
    }
}

fn main() {
    let mut s = S {
        field: Some("a".to_owned()),
    };
    f(&mut s);
    println!("{:?}", s.field);
}

Here's the compiler message:

error[E0507]: cannot move out of `arg.field.0` which is behind a mutable reference
 --> src/main.rs:6:11
  |
6 |     match arg.field {
  |           ^^^^^^^^^ help: consider borrowing here: `&arg.field`
7 |         Some(s) => s.push('a'),
  |              -
  |              |
  |              data moved here
  |              move occurs because `s` has type `std::string::String`, which does not implement the `Copy` trait

error[E0596]: cannot borrow `s` as mutable, as it is not declared as mutable
 --> src/main.rs:7:20
  |
7 |         Some(s) => s.push('a'),
  |              -     ^ cannot borrow as mutable
  |              |
  |              help: consider changing this to be mutable: `mut s`

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0507, E0596.
For more information about an error, try `rustc --explain E0507`.
error: could not compile `playground`.

(Stable 1.45.0) (Beta 1.46.0-beta.1) (Nightly 1.47.0-nightly)

However, applying the suggestions results in:

fn f(arg: &mut S) {
    match &arg.field {
        Some(mut s) => s.push('a'),
        None => {}
    }
}

which doesn't work either.

(Related post on the Rust Programming Language Forum: Having trouble using Struct Option var)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-bugCategory: This is a bug.D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.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