Email me

Rust errors / Ownership and borrowing

Rust compiler error · checked with rustc 1.99.0

Rust error E0500: closure requires unique access to `*jon_snow` but it is already borrowed

What it meansA borrowed variable was used by a closure.

What rustc prints

error[E0500]: closure requires unique access to `*jon_snow` but it is already borrowed
 --> main.rs:3:18
  |
2 |     let nights_watch = &jon_snow;
  |                        --------- borrow occurs here
3 |     let starks = || {
  |                  ^^ closure construction occurs here
4 |         *jon_snow = 3; // error: closure requires unique access to `jon_snow`
  |         --------- second borrow occurs due to use of `*jon_snow` in closure
...
7 |     println!("{}", nights_watch);
  |                    ------------ first borrow later used here

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.

E0500Ownership and borrowing
Activein rustc 1.99.0
6related errors linked below

The compiler team's explanation

A borrowed variable was used by a closure.

Erroneous code example:

fn you_know_nothing(jon_snow: &mut i32) {
    let nights_watch = &jon_snow;
    let starks = || {
        *jon_snow = 3; // error: closure requires unique access to `jon_snow`
                       //        but it is already borrowed
    };
    println!("{}", nights_watch);
}

In here, jon_snow is already borrowed by the nights_watch reference, so it cannot be borrowed by the starks closure at the same time. To fix this issue, you can create the closure after the borrow has ended:

fn you_know_nothing(jon_snow: &mut i32) {
    let nights_watch = &jon_snow;
    println!("{}", nights_watch);
    let starks = || {
        *jon_snow = 3;
    };
}

Or, if the type implements the Clone trait, you can clone it between closures:

fn you_know_nothing(jon_snow: &mut i32) {
    let mut jon_copy = jon_snow.clone();
    let starks = || {
        *jon_snow = 3;
    };
    println!("{}", jon_copy);
}

From rustc --explain E0500 (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