skip to content

In Rust, what do E0505 and E0506 report, and how do you fix a move or assignment while a borrow is still live?

level: middleimportance: should knowfreq 45%

answer

  1. the owner changes under a loan
  2. E0505 moves, E0506 assigns
  3. the old value would be dropped
  4. finish the borrow, or borrow instead

basics

~20 s

E0505 reports a move out of a value that is still borrowed; E0506 an assignment to one. Either would leave the reference seeing dropped or replaced data. Finish the borrow first, borrow instead of moving, or copy out what you need.

solid answer

~50 s

E0505, "cannot move out of `names` because it is borrowed", fires when a value is moved, for example passed by value to a function or to `drop`, while a reference into it is used later: the new owner may free it, so the reference would dangle. E0506, "cannot assign to `ed.selected` because it is borrowed", fires when a borrowed place is overwritten: assignment drops the old `String`, and even for an `i32` a shared reference would see the value change under it. Both appear only when the borrow is used after the move or assignment. The fixes: reorder so the reference's last use comes first; pass `&names` if the callee only reads; copy out the one field you need (`names[0].clone()`, not the whole vector); or use `mem::replace` to install the new value and keep the old one as an owned value. E0502 and E0499 are the neighbouring errors for two conflicting borrows.

code

rust · 7 lines
rust
fn archive(names: Vec<String>) -> usize { names.len() }
fn main() {
    let names = vec![String::from("a"), String::from("b")];
    let first = &names[0];
    let n = archive(names);
    println!("{first} {n}");
}

go deeper

for a junior

Recall the pair: E0505 is a move while borrowed, E0506 an assignment while borrowed, and both go away when the reference is no longer used afterwards.

for a middle

Explain why each would leave a dangling or lying reference, read the three labels, and pick between reordering, borrowing, copying one field or mem::replace.

for a senior

Reject wholesale clones in review when reordering or a narrower borrow does the job, and recognise when a getter hides a field-level borrow behind a whole-struct borrow.

for a principal

Treat repeated E0505 at API boundaries as a signature problem: functions that only read should borrow, and only a function that must keep or destroy the value should take it by value.

## One family of borrow errors rustc's borrow checker reports several errors that all mean "something happened to a value while a borrow of it was still needed". Knowing which is which tells you what the conflicting operation was. | E-code | rustc's message | The operation that conflicts | |---|---|---| | E0499 | cannot borrow `x` as mutable more than once at a time | a second `&mut` | | E0502 | cannot borrow `x` as mutable because it is also borrowed as immutable (or the reverse) | a borrow of the other kind | | E0505 | cannot move out of `x` because it is borrowed | a **move** | | E0506 | cannot assign to `x` because it is borrowed | an **assignment** | E0382, use of a moved value, is a different situation: no borrow is involved, the owner itself was moved and then used. ## E0505: moving while borrowed In a graph editor, `let first = &names[0];` borrows a `Vec<String>` of node names. `archive(names)` then **moves** the vector into a function that takes `Vec<String>` by value. The callee owns it now and drops it when it returns, freeing every `String`. If `first` is read afterwards, it points into freed memory, so rustc rejects the move: - "borrow of `names` occurs here" marks `&names[0]`; - "move out of `names` occurs here" marks the argument; - `borrow later used here` marks the read of `first`. `drop(names)` is a move too, so it produces the same E0505. The error-code index lists the remedies: avoid the move, release the borrow before the move, or make the type `Copy` when that is honest for it. ## E0506: assigning while borrowed `let sel = &ed.selected;` borrows a field; `ed.selected = String::from("node-2");` overwrites it. Assignment **drops the old value** first, so `sel` would point at a freed `String`. The rule is not only about heap memory: `let r = &zoom; zoom = 2;` on an `i32` is also E0506 when `r` is read later, because a shared reference promises the value does not change while it is live. The report names the **place**, not just the variable: "cannot assign to `ed.selected` because it is borrowed". A borrow of one field does not block assignment to a different field of the same struct, because the checker tracks fields separately when you access them directly. ## Where a move hides E0505 is easy to read once you notice that many operations are moves: - calling a method that takes `self`, such as `names.into_iter()`, while `first` still borrows `names`; - passing the value to a function or a constructor by value, including `drop`; - returning the value, or storing it into a struct field or a collection; - a `for` loop over the value itself rather than over `&names`. Each of these hands ownership elsewhere, and the new owner is free to drop or change the value. ## How to fix either 1. **Reorder.** Move the last use of the reference above the move or the assignment. Under non-lexical lifetimes that ends the borrow, and nothing else changes. 2. **Borrow instead of move.** If `archive` only reads the names, change it to take `&[String]` and pass `&names`. 3. **Copy out the part you need.** `let first = names[0].clone();` clones one `String` and leaves no borrow behind; a `Copy` field can simply be read by value. 4. **Swap in the new value and keep the old one.** `let previous = mem::replace(&mut ed.selected, String::from("node-2"));` gives you the old `String` as an owned value, so there is nothing left to borrow. ## Read the compiler's help critically For E0505 rustc adds `help: consider cloning the value if the performance cost is acceptable` and proposes `&names.clone()[0]`. That compiles, but it clones the **whole vector** to read one element. The help is a valid local patch, not a design recommendation: - cloning one element is usually enough; - reordering costs nothing at run time; - a callee that only reads should borrow. Apply the cheapest fix that keeps ownership clear, and leave cloning for values that are small or genuinely need two owners.

  • Why is assigning to a borrowed `i32` also E0506, when no memory is freed?
    A live shared reference guarantees the value does not change while it is in use. Overwriting `zoom` while `r` is still read later would break that guarantee, so rustc rejects the assignment for any type, not only for types that own heap memory.
  • Does borrowing `ed.selected` stop you from assigning to `ed.zoom`?
    No, when both are accessed directly as fields of a local or of `self`: the borrow checker tracks `ed.selected` and `ed.zoom` as separate places. It cannot see through a method call, though, so borrowing via a `&self` getter borrows the whole struct.

  • E0505 and E0506 mean the same thing as E0382, use after move.
  • Assigning to a borrowed i32 is fine because integers are Copy.
  • Borrowing one field of a struct blocks assignment to every other field, even when accessed directly.
  • The compiler's clone suggestion is always the right fix for E0505.
  • drop(names) is not a move, so it cannot cause E0505.