Skip to content

Closure captures immutable reference when mutable reference is necessary #88372

Closed
@narpfel

Description

@narpfel

Code

I tried this code:

fn solve<F>(validate: F) -> Option<u64>
where
    F: Fn(&mut [i8; 1]),
{
    let mut position: [i8; 1] = [1];
    Some(0).map(|_| {
        validate(&mut position);
        let [_x] = position;
        0
    })
}

fn main() {
    solve(|_| ());
}

I expected to see this happen: The code should compile.

Instead, this happened: This compiler error is thrown:

$ rustc --version
rustc 1.56.0-nightly (0afc20860 2021-08-25)
$ rustc main.rs
error[E0596]: cannot borrow `position` as mutable, as it is behind a `&` reference
 --> main.rs:7:18
  |
7 |         validate(&mut position);
  |                  ^^^^^^^^^^^^^ cannot borrow as mutable

warning: variable does not need to be mutable
 --> main.rs:5:9
  |
5 |     let mut position: [i8; 1] = [1];
  |         ----^^^^^^^^
  |         |
  |         help: remove this `mut`
  |
  = note: `#[warn(unused_mut)]` on by default

error: aborting due to previous error; 1 warning emitted

For more information about this error, try `rustc --explain E0596`.

Version it worked on

It most recently worked on: nightly-2021-07-11 (also works on stable 1.54). Starting from nightly-2021-07-12, I get the error shown above.

Version with regression

rustc --version --verbose: current nightly

$ rustc --version --verbose
rustc 1.56.0-nightly (0afc20860 2021-08-25)
binary: rustc
commit-hash: 0afc20860eb98a29d9bbeea80f2acc5be38c6bf3
commit-date: 2021-08-25
host: x86_64-unknown-linux-gnu
release: 1.56.0-nightly
LLVM version: 13.0.0

Also broken on 1.55 beta 7:

$ cargo +beta rustc -- --version --verbose
rustc 1.55.0-beta.7 (bf16ca353 2021-08-21)
binary: rustc
commit-hash: bf16ca353c82d9051dbd1a4cfc5a01a1800578e9
commit-date: 2021-08-21
host: x86_64-unknown-linux-gnu
release: 1.55.0-beta.7
LLVM version: 12.0.1

Both installed via rustup.

Backtrace

n/a


Additional information

This seems similar to #87814, which was fixed in #88266 / b03ccac (which AFAIU should be included in nightly-2021-08-25), but it still does not work.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)C-bugCategory: This is a bug.regression-from-stable-to-betaPerformance or correctness regression from stable to beta.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions