Skip to content

Invalid suggestion for mutability correction in error message #33819

Closed

Description

@Vtec234

The compiler makes an invalid suggestion for how to correct the immutability of a reference in a match block. To reproduce, try to compile the following code:

use std::fs::File;
use std::io::Write;

fn main() {
    let mut op = Some(File::open("").unwrap());
    match op {
        Some(ref mut f) => { write!(f, "!").unwrap();  },
        None => {},
    }
}

On stable and beta, the compiler will print:

<anon>:7:33: 7:34 error: cannot borrow immutable local variable `f` as mutable
<anon>:7         Some(ref f) => { write!(f, "!").unwrap();  },
                                     ^
<anon>:7:26: 7:40 note: in this expansion of write! (defined in <std macros>)
<anon>:7:14: 7:19 help: to make the local variable mutable, use `mut` as shown:
<anon>:          Some(mut ref f) => { write!(f, "!").unwrap();  },

On nightly, it will print:

error: cannot borrow immutable local variable `f` as mutable
 --> <anon>:7:33
7 |>         Some(ref f) => { write!(f, "!").unwrap();  },
  |>              -----              ^ cannot borrow mutably
  |>              |
  |>              use `mut ref f` here to make mutable

Both of these suggestions are erroneous, as mut ref f is invalid syntax, and should be ref mut f.

Activity

  1. durka commented on May 23, 2016

    @durka
    Contributor

    Actually if you write ref mut v it doesn't work either, as then v is an immutable &mut i32. So I guess no note should be printed, and possibly mut ref [mut] $ident should be allowed in patterns.

  2. added a commit that references this issue on May 24, 2016
    4280992
  3. Vtec234 commented on May 24, 2016

    @Vtec234
    ContributorAuthor

    You are right, but it was just my mistake. I updated the original code to the simplest thing I could think of which invokes the right error message and is fixable by ref mut.

  4. sophiajt commented on May 24, 2016

    @sophiajt
    Contributor

    In this particular case, but is that true in the general case? The heuristics for when to suggest something are necessarily going to have corner cases (which hopefully will get smoothed over time)

  5. added a commit that references this issue on May 28, 2016
    fe19b47
  6. added a commit that references this issue on Feb 1, 2021
  7. added a commit that references this issue on Feb 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lints

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions