Rust

Fix Rust E0507 "cannot move out of ..." — Vec Index, HashMap Index, a Shared Reference, a Struct Field, and a Mutable Reference

A value was asked to leave a place it does not own — an indexed element, a map value, or data behind a reference — and the compiler refused to leave a hole behind. This guide separates the places: a Vec element, a HashMap value, a value behind a shared reference, a struct field behind a reference, and a field behind a mutable reference — and matches each one to borrowing, cloning, removing, or taking with a replacement.

Written November 22, 2026 · Tested with Rust 1.99.0 · 19 min read

By the end of this guide
  • The rule underneath: a move needs a place you own
  • How to read the diagnostic
  • The first failure: moving out of a Vec element by index
  • The second failure: moving out of a HashMap value by index

Written November 22, 2026

Tested with Rust 1.99.0

What this guide is

Error E0507 is the move that would leave a hole. The error codes index gives it in one sentence: a value that does not implement the Copy trait was moved out of a borrowed value. Moving a String transfers ownership of its heap allocation, so after the move the old place must not be used again. When the old place is an element inside a vector, a value inside a map, or a field inside a struct that someone else still holds a reference to, the compiler cannot mark just that piece as gone — so it refuses the move outright, and the fix is always a different way of getting the value: borrow it, clone it, remove it through an operation that repairs the container, or take it while leaving a valid replacement behind.

The five places this guide works through cover most E0507 reports in ordinary code. Indexing a Vec and assigning the element to a String. Indexing a HashMap the same way. Returning *s from a function that only borrowed a String. Returning a field from a function that only borrowed the struct. And returning a field from a &mut self method, where the caller still owns the struct afterward. In each family the failing program is small, the full compiler output is shown, and the fix is the smallest change that respects who owns what.

Build every program in this guide with rustc --edition 2021. In the compiler transcripts below, the file names are the bare names shown on the command line.

The rule underneath: a move needs a place you own

Ownership in the Rust Book chapter on ownership is a transfer rule: assigning or passing a value of a non-Copy type moves it, and the previous owner may not use it afterward. A reference changes the picture. The chapter on references and borrowing defines a reference as a way to refer to a value without taking ownership of it — so code working through a reference never had the right to move the value out in the first place.

Indexing has the same shape, for a less obvious reason. The std documentation for the Index trait defines indexing as an operation that returns a reference to the indexed output. Writing v[0] in a place that reads the value therefore gives you &String, not String, even when v itself is a local variable you own: the index expression is a borrow of the element, and a move out of that borrow is exactly what E0507 forbids. That is why the same error appears for a vector you created two lines earlier and for a struct you only borrowed — the immediate place, not the ultimate owner, decides.

Two consequences follow, and they organize every fix below:

  • Types that implement Copy never produce this error. Copying an i32 out of a vector leaves the original intact bit for bit, so no hole exists. E0507 names the missing trait in every diagnostic: "value has type String, which does not implement the Copy trait".
  • A move out is legal when an operation accounts for the hole. Vec::remove shifts the later elements down, HashMap::remove deletes the entry, and std::mem::take leaves the type's default in the field — each operation leaves the source in a valid state, which a plain index or field access cannot promise.

How to read the diagnostic

The first line names the place, and the place tells you the family. "cannot move out of index of Vec<String>" and "cannot move out of index of HashMap<...>" are the container families. "which is behind a shared reference" and "which is behind a mutable reference" are the reference families — the wording after "behind" tells you whether std::mem::take is even available, because taking needs a mutable reference.

The line under the caret states the cause in the same words every time: the move occurs because the value has a type that does not implement Copy. If that type were Copy, the same code would compile unchanged, which is a useful check on whether you are really looking at E0507 or at a borrow or lifetime error wearing similar words.

The help lines propose the two cheapest repairs when they apply: "consider borrowing here", which changes the binding to a reference, and "consider cloning the value if the performance cost is acceptable", which is the compiler naming the Clone trait — explicit duplication, available when the original must stay where it is. Where neither help appears as the right answer, the container or field needs an operation the help cannot guess: remove the element, or take the field.

The first failure: moving out of a Vec element by index

A vector owns its elements in one allocation, in order. Assigning v[0] to a String variable would move the first element's allocation out and leave an invalid element in its place, and no later code could tell the slot was empty:

Rust
fn main() {
    let v = vec![String::from("alpha"), String::from("beta")];
    let s: String = v[0];
    println!("{s} {}", v.len());
}
Terminal
$ rustc --edition 2021 fail_vec.rs -o fail_vec
error[E0507]: cannot move out of index of `Vec<String>`
 --> fail_vec.rs:3:21
  |
3 |     let s: String = v[0];
  |                     ^^^^ move occurs because value has type `String`, which does not implement the `Copy` trait
  |
help: consider borrowing here
  |
3 |     let s: String = &v[0];
  |                     +
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let s: String = v[0].clone();
  |                         ++++++++

error: aborting due to 1 previous error

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

The first line names the container, not the element: "cannot move out of index of Vec<String>". The vector is the place that would be left broken. Both help lines are real fixes for the reading case — borrow with &v[0] when the code only needs to look, or write v[0].clone() when it needs an owned copy and the vector must keep its element. When the element should actually leave the vector, the operation is remove, whose Vec documentation describes it as removing and returning the element at the given index, shifting every later element one place to the left:

Rust
fn main() {
    let mut v = vec![String::from("alpha"), String::from("beta")];
    let s: String = v.remove(0);
    println!("{s} {}", v.len());
}
Terminal
$ rustc --edition 2021 fix_vec.rs -o fix_vec
$ ./fix_vec
alpha 1

The output shows both halves of the contract: the caller got alpha, and the vector is still usable with one element left. swap_remove is the faster sibling for cases where order does not matter: it moves the last element into the vacated slot instead of shifting. Reach for remove when order matters, swap_remove when it does not, and clone when the element must stay.

The second failure: moving out of a HashMap value by index

Indexing a map looks the value up and returns a reference to it, the same Index contract as the vector — and it panics when the key is absent, which indexing a vector also does for an out-of-range index. Moving the value out by index would leave an entry whose key points at nothing:

Rust
use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert("key", String::from("alpha"));
    let s: String = map["key"];
    println!("{s}");
}
Terminal
$ rustc --edition 2021 fail_map.rs -o fail_map
error[E0507]: cannot move out of index of `HashMap<&str, String>`
 --> fail_map.rs:6:21
  |
6 |     let s: String = map["key"];
  |                     ^^^^^^^^^^ move occurs because value has type `String`, which does not implement the `Copy` trait
  |
help: consider borrowing here
  |
6 |     let s: String = &map["key"];
  |                     +
help: consider cloning the value if the performance cost is acceptable
  |
6 |     let s: String = map["key"].clone();
  |                               ++++++++

error: aborting due to 1 previous error

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

The diagnostic mirrors the vector case almost word for word, with the map type in place of the vector type. The reading fixes mirror it too: borrow the value, or clone it with map["key"].clone(), or — usually better for a lookup that might miss — use map.get("key") and clone from the Option it returns, so a missing key is handled instead of panicking. When the entry should leave the map, remove is the operation that accounts for the hole: the HashMap documentation shows remove deleting an entry by key, and it returns the value as an Option, so the caller decides what an absent key means:

Rust
use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert("key", String::from("alpha"));
    let s: String = map.remove("key").unwrap();
    println!("{s} {}", map.len());
}
Terminal
$ rustc --edition 2021 fix_map.rs -o fix_map
$ ./fix_map
alpha 0

The length in the output is the proof that the entry is gone, not copied: the map is empty afterward, and s owns the string that was in it. If the code only needed the text, cloning through get keeps the entry for the next lookup at the cost of one allocation.

The third failure: moving out from behind a shared reference

This is the shape the error codes index itself uses: a function receives &String and tries to return the String behind it. A shared reference may be copied freely and read freely, but it confers no ownership, so dereferencing it cannot produce an owned value of a non-Copy type:

Rust
fn take(s: &String) -> String {
    *s
}

fn main() {
    let name = String::from("alpha");
    let owned = take(&name);
    println!("{owned} {name}");
}
Terminal
$ rustc --edition 2021 fail_ref.rs -o fail_ref
error[E0507]: cannot move out of `*s` which is behind a shared reference
 --> fail_ref.rs:2:5
  |
2 |     *s
  |     ^^ move occurs because `*s` has type `String`, which does not implement the `Copy` trait
  |
help: consider cloning the value if the performance cost is acceptable
  |
2 -     *s
2 +     s.clone()
  |

error: aborting due to 1 previous error

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

Nothing here is a container problem. The value is whole, in one place, and still out of reach, because the function never owned it — the caller does, and the caller uses name again after the call, as main shows. The fix the compiler proposes is the honest one: clone the value, using the Clone implementation that String provides, so the caller keeps its string and the function returns a new one:

Rust
fn take(s: &String) -> String {
    s.clone()
}

fn main() {
    let name = String::from("alpha");
    let owned = take(&name);
    println!("{owned} {name}");
}
Terminal
$ rustc --edition 2021 fix_ref.rs -o fix_ref
$ ./fix_ref
alpha alpha

Both strings print because there really are two strings now. When a clone is waste the design does not need, the other repairs change the signature instead of the body: return &str borrowed from the input when the caller can work with a view, or take String by value when the function is meant to consume it. Choosing among clone, borrow, and consume is the actual design decision this error is pointing at — the compiler only insists that you make it explicitly.

The fourth failure: moving a struct field out through a shared reference

A field access through a reference is still behind that reference. Writing holder.name as the return value tries to move one field out of a struct the function only borrowed, which would leave the borrowed struct with a missing field for its real owner to trip over:

Rust
struct Holder {
    name: String,
}

fn get(holder: &Holder) -> String {
    holder.name
}

fn main() {
    let h = Holder { name: String::from("alpha") };
    println!("{} {}", get(&h), h.name);
}
Terminal
$ rustc --edition 2021 fail_holder.rs -o fail_holder
error[E0507]: cannot move out of `holder.name` which is behind a shared reference
 --> fail_holder.rs:6:5
  |
6 |     holder.name
  |     ^^^^^^^^^^^ move occurs because `holder.name` has type `String`, which does not implement the `Copy` trait
  |
help: consider cloning the value if the performance cost is acceptable
  |
6 |     holder.name.clone()
  |                ++++++++

error: aborting due to 1 previous error

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

The first line names the field path, holder.name, which is the tell that the move is partial as well as borrowed: even the struct's owner could not hand this field to a function this way and keep using the struct as a whole without accounting for the missing piece. Through a shared reference the repair set is the same as for a bare borrowed value — clone the field, or change what the function returns:

Rust
struct Holder {
    name: String,
}

fn get(holder: &Holder) -> String {
    holder.name.clone()
}

fn main() {
    let h = Holder { name: String::from("alpha") };
    println!("{} {}", get(&h), h.name);
}
Terminal
$ rustc --edition 2021 fix_holder.rs -o fix_holder
$ ./fix_holder
alpha alpha

The output again shows the original intact next to the returned copy. Returning &holder.name, or a &str view of it, avoids the allocation when the caller only reads. What a shared reference can never do is empty the field: there is no way to leave a replacement behind through &Holder, because writing through a shared reference is not allowed at all. That operation needs the mutable case, next.

The fifth failure: moving a field out behind a mutable reference

A method that takes &mut self may write to the struct, but it still may not move a field out and leave the field invalid — the struct outlives the call, and its owner will read it afterward. So the plain field return fails here too, with "mutable reference" in place of "shared reference":

Rust
struct Holder {
    name: String,
}

impl Holder {
    fn take_name(&mut self) -> String {
        self.name
    }
}

fn main() {
    let mut h = Holder { name: String::from("alpha") };
    println!("{}", h.take_name());
}
Terminal
$ rustc --edition 2021 fail_mutfield.rs -o fail_mutfield
error[E0507]: cannot move out of `self.name` which is behind a mutable reference
 --> fail_mutfield.rs:7:9
  |
7 |         self.name
  |         ^^^^^^^^^ move occurs because `self.name` has type `String`, which does not implement the `Copy` trait
  |
help: consider cloning the value if the performance cost is acceptable
  |
7 |         self.name.clone()
  |                  ++++++++

error: aborting due to 1 previous error

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

The mutable reference is what unlocks the real take. The std documentation for std::mem::take defines it as taking the value out of a mutable reference and leaving the default value of the type in its place, and notes the case it exists for: a field that cannot simply be copied out of a struct that is behind a reference, where the struct itself must be left intact. String's default is the empty string, so the field stays valid:

Rust
struct Holder {
    name: String,
}

impl Holder {
    fn take_name(&mut self) -> String {
        std::mem::take(&mut self.name)
    }
}

fn main() {
    let mut h = Holder { name: String::from("alpha") };
    println!("{} [{}]", h.take_name(), h.name);
}
Terminal
$ rustc --edition 2021 fix_mutfield.rs -o fix_mutfield
$ ./fix_mutfield
alpha []

The brackets in the output show the replacement: the caller received alpha, and h.name is now the empty string — present, valid, and empty, not missing. When the replacement should be a specific value rather than the default, the sibling function std::mem::replace swaps a supplied value in and returns the old one. The same pattern covers an Option field, where the field's own take method leaves None behind and returns the old Some value — the Option documentation describes that method in the same take-and-leave language. Clone remains available in this family too, and is the right choice when the field must keep its value.

The fixes in reach order

  • Borrow first when the code only reads: &v[0], &map[key], a &str or &String return. No allocation, no hole, and the diagnostic's own first help line points here.
  • Clone when an owned value is needed and the original must stay: v[0].clone(), map.get(key).cloned(), s.clone(), holder.name.clone(). One allocation per clone, and the source is untouched.
  • Remove when a container element should really leave: Vec::remove to keep order, Vec::swap_remove when order does not matter, HashMap::remove to take the value and delete the entry in one operation.
  • Take or replace when a field behind a mutable reference should be emptied: std::mem::take to leave the default, std::mem::replace to leave a value you choose, and Option::take for an Option field, which leaves None.
  • Change the signature when none of the above matches the intent: take the value by value to consume it, or return a reference when the caller can borrow. The error often means the signature promised ownership the design never had.
  • Iterate by value when the whole container is being consumed: for s in v and map.into_iter() move each element legally, because the container itself is being moved and dismantled, not borrowed.

Traps

  • Adding .clone() everywhere silences the error and hides the design question. Some of those clones are the right fix; others are an allocation on a hot path where a borrow was all the code needed. Read the first line's place name before choosing.
  • remove and indexing panic on a missing position in the same way — an out-of-range index for a vector, and HashMap::remove returns None instead of panicking, so the two containers differ here: check which behavior the code needs before swapping one operation for the other.
  • std::mem::take needs a type with a sensible default. It works cleanly for String, Vec, and Option fields; for a field whose default would be a lie the code later trusts, replace with an explicit value, or restructuring the field as an Option, is the honest version.
  • Moving a field out of a struct you own outright is a different, legal operation — a partial move — as long as the moved field is not used again and the struct is not used as a whole. Code that compiled as an owned partial move starts failing with E0507 as soon as the struct arrives behind a reference, which is why a signature change can surface this error far from the field itself.
  • A Copy derive does not fix a String field. Copy requires every field to be Copy, and String is not, because copying it bit for bit would duplicate ownership of one heap allocation. Types that hold heap data are Clone, not Copy.
  • Dereferencing a Box you own is not this error. Moving out of an owned box is a special legal move, because the box is dismantled by it; the same dereference through a borrowed box is E0507, because the box belongs to someone else.

Decision summary

  • The first line says "index of Vec": borrow or clone to read, remove to keep order, swap_remove when order does not matter.
  • The first line says "index of HashMap": get and clone to read without panicking on a missing key, remove to take the value and delete the entry.
  • The first line says "behind a shared reference": clone for an owned copy, or change the signature to borrow out or consume in — taking is impossible through a shared reference.
  • The first line names a field path behind a shared reference: clone the field, or return a reference to it.
  • The first line says "behind a mutable reference": std::mem::take for a default replacement, std::mem::replace for a chosen replacement, Option::take for an Option field, clone when the field must stay.
  • The value's type implements Copy in a sibling case that compiles: the difference is the type, not the shape — the non-Copy type needs one of the operations above.

Checklist

  • The first line of the diagnostic read, and the place it names — index, dereference, or field path — identified.
  • The borrow-or-own question answered before editing: does this code read the value, need its own copy, or need the value itself out of its current place?
  • Container elements taken out with remove, swap_remove, or the map's remove, never by index assignment.
  • Fields behind a mutable reference taken with mem::take, mem::replace, or Option::take, so the struct is left valid.
  • Nothing cloned on a path where a borrow would have served, and no borrow kept where the caller genuinely needs ownership.
  • The fixed program run, and its output checked for both halves: the value received, and the source left in the state the fix promised.

Sources

Keep Exploring