Skip to content

Closure captures immutable reference when mutable reference is necessary #87814

Closed
@ldm0

Description

@ldm0

Code

I tried this code:

fn main() {
    let mut schema_all = vec![];
    (0..42).for_each(|_x| match Err(()) as Result<(), _> {
        Ok(()) => schema_all.push(()),
        Err(_) => (),
    });
}

I expected to see this happen: cargo build success

Instead, this happened: cargo build failed

error[E0596]: cannot borrow `schema_all` as mutable, as it is behind a `&` reference
 --> src/main.rs:4:19
  |
4 |         Ok(()) => schema_all.push(()),
  |                   ^^^^^^^^^^ cannot borrow as mutable

warning: variable does not need to be mutable
 --> src/main.rs:2:9
  |
2 |     let mut schema_all = vec![];
  |         ----^^^^^^^^^^
  |         |
  |         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-03-16

Version with regression

rustc --version --verbose:

nightly-2021-03-17

Metadata

Metadata

Assignees

Labels

A-closuresArea: Closures (`|…| { … }`)C-bugCategory: This is a bug.P-mediumMedium priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.regression-from-stable-to-stablePerformance or correctness regression from one stable version to another.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions