Email me

Rust errors / Ownership and borrowing

Rust compiler error · checked with rustc 1.99.0

Rust error E0596: cannot borrow as mutable, as it is not declared as mutable

What it meansYou need a mutable borrow of something that is not mutable: a let without mut, or data reached through a shared & reference.

What rustc prints

error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable
 --> main.rs:4:9
  |
4 | let y = &mut x; // error: cannot borrow mutably
  |         ^^^^^^ cannot borrow as mutable
  |
help: consider changing this to be mutable
  |
3 | let mut x = 1;
  |     +++

Real output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.

Why it happens

  • let v = Vec::new(); v.push(1);
  • A method takes &self but changes a field (needs &mut self).
  • A closure that mutates captured state stored in a non-mut binding.

How to fix it

1. Declare it mut

let mut v = Vec::new();
v.push(1);

2. Take &mut self

impl Counter {
    fn bump(&mut self) { self.n += 1; }
}

3. Interior mutability

When shared access must still change something: Cell, RefCell, Mutex, atomics.

use std::cell::Cell;
struct Hits { n: Cell<u32> }
impl Hits { fn hit(&self) { self.n.set(self.n.get() + 1); } }

Other wordings of this error

cannot borrow as mutable, as it is not declared as mutable, cannot borrow as mutable, as it is behind a `&` reference, consider changing this to be mutable

E0596Ownership and borrowing
Activein rustc 1.99.0
8related errors linked below

The compiler team's explanation

This error occurs because you tried to mutably borrow a non-mutable variable.

Erroneous code example:

let x = 1;
let y = &mut x; // error: cannot borrow mutably

In here, x isn't mutable, so when we try to mutably borrow it in y, it fails. To fix this error, you need to make x mutable:

let mut x = 1;
let y = &mut x; // ok!

From rustc --explain E0596 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.

Related errors

All 518 Rust error codes · Rust crate data · Glossary

Up next

Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →

Did this answer your question?

Get the receipts by email.

What my AI agents tried this week, with the real numbers: what worked, what flopped, what made money. One email when there is something worth reading.

No spam, never sold. Every email has a one-click unsubscribe.

Popular in the shop

All 124 tools →

Browse: Bundles and kitsHome, family and schoolMoney and businessAI toolsSports and fitnessMaking and hobbiesFood and drinkIndie dev and launchTrading and quant

Free: Landing page teardown iPhone app cost calculator LLM API cost calculator Paid online: $49 Launch Check App builds Articles FAQ