Rust E0507: cannot move out of a shared reference
E0507 means you asked to move a field through &self. Borrow instead, or move it out with Option::take or mem::take, and leave the source valid.

Introduction & Quick Summary
The borrow checker rejects a move through a reference:
error[E0507]: cannot move out of `self.value` which is behind a shared reference
--> src/main.rs:8:9
|
8 | self.value
| ^^^^^^^^^^ move occurs because `self.value` has type `String`,
| which does not implement the `Copy` traitYou have a &self (or a &T) and are asking to hand ownership of a field out of it. A shared reference guarantees the value stays put for as long as the borrow lives, so moving its contents away would leave the original partially invalid — the compiler refuses, and it is right to.
Quick answer: choose the cheapest of four shapes that fits the caller.
fn value(&self) -> &str { &self.value } // borrow: no copy at all
fn value(&self) -> String { self.value.clone() } // copy: caller owns a duplicate
fn take(&mut self) -> Option<String> { self.value.take() } // move the field out, leave None
fn take(&mut self) -> String { std::mem::take(&mut self.value) } // move, leave DefaultMost E0507 reports are fixed by the first one. The getter that returns String where &str would do is a design decision that forces a clone on every call, and it is the one people reach for because it makes the error disappear.
Core Mechanics, Signatures & Reproducible Setup
Ownership rules behind the error, in one place:
- Reading a field through
&Tcopies primitive andCopytypes and borrows everything else. - Producing an owned
Tfrom a&Trequires eitherClone(an explicit copy) or a move from a place you own. - A move from behind a reference is possible only when the source can be left in a valid state — which is what
Option::take,mem::take, andmem::replaceprovide.
Reproduce the error and its neighbours in one file:
struct Config { name: String }
impl Config {
fn name_bad(&self) -> String { self.name } // E0507
fn name_ref(&self) -> &str { &self.name } // fine
fn name_clone(&self) -> String { self.name.clone() }
}
fn consume(v: Vec<String>) {
for s in v { println!("{s}"); } // consumes the vec
}
fn borrow(v: &Vec<String>) {
for s in v { println!("{s}"); } // s is &String, no move of the vec
}Compile with cargo check rather than cargo build; the borrow checker is the same and it is faster.
Copy and Clone are not interchangeable. Copy is an implicit bitwise duplicate, allowed only for types with no destructor and no heap allocation; Clone is an explicit method that can allocate. Deriving Copy on a struct containing String fails with E0204, which is the compiler telling you that the type's ownership cannot be duplicated implicitly.
The four places this call shape appears:
| Call site | Compiler sees | What to change |
|---|---|---|
| a getter returning a field | &self | borrow, or clone deliberately |
match *s on a borrowed enum | shared reference | match s and bind by reference |
for x in vec then use vec | move of the collection | for x in &vec |
a field of a Drop type | partial move forbidden | Option plus take |
Key Comparison Table
Choosing the extraction shape:
| Intent | Signature | Cost | Leaves the source |
|---|---|---|---|
| read without copying | fn f(&self) -> &str | none | untouched |
| return an owned copy | fn f(&self) -> String | one allocation | untouched |
| move out once | fn f(&mut self) -> Option<T> | none | None |
| move out, keep usable | fn f(&mut self) -> T where T: Default | none | Default::default() |
| share ownership | fn f(&self) -> Rc<T> / Arc<T> | refcount bump | untouched |
| avoid the clone lazily | fn f(&self) -> Cow<'_, str> | none until mutation | untouched |
Which adjacent error you might be looking at:
| Error | Meaning | Typical fix |
|---|---|---|
| E0507 | move out of a shared reference | borrow, clone, or take |
| E0509 | move out of a type that implements Drop | mem::take or Option |
| E0382 | use of a moved value | clone, borrow, or reorder |
| E0502 / E0499 | conflicting borrows | narrow the borrow scope |
| E0515 | returning a reference to a temporary | return owned data |
| E0204 | Copy on a type with a destructor | use Clone instead |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Getters: borrow first, clone only when needed
pub struct User { pub email: String }
impl User {
pub fn email(&self) -> &str { &self.email } // preferred
pub fn email_owned(&self) -> String { self.email.clone() } // for APIs that need ownership
}Returning &str lets callers choose: a serde_json field can borrow it, and a function that stores it can call .to_owned() itself. Returning String takes that choice away and pays for an allocation on every call.
2. Moving a field out of &mut self with Option::take
pub struct Connection { socket: Option<TcpStream> }
impl Connection {
pub fn close(&mut self) -> Option<TcpStream> {
self.socket.take() // leaves None, hands ownership out
}
pub fn send(&mut self, data: &[u8]) -> std::io::Result<()> {
match self.socket.as_mut() { // borrow the inside, do not move it
Some(s) => s.write_all(data),
None => Err(std::io::Error::other("closed")),
}
}
}take is the idiomatic answer for a field that can be absent, and it composes with ? and if let. Storing the value directly and using mem::replace with a dummy works too, but forces the dummy to be constructible.
3. std::mem::take for fields with a Default
#[derive(Default)]
struct Buffer { data: Vec<u8> }
impl Buffer {
fn drain(&mut self) -> Vec<u8> {
std::mem::take(&mut self.data) // moves the vec, leaves Vec::new()
}
}mem::take requires T: Default; mem::replace takes an explicit replacement and works for any type. Both are const fn-friendly and allocate nothing, which matters in a hot path where clone() would.
4. match on a borrowed enum
enum State { Idle, Busy(String) }
// E0507: moving the String out of a shared reference
fn label(s: &State) -> String {
match s {
State::Busy(name) => name.clone(),
State::Idle => "idle".into(),
}
}Matching on &State binds name as &String thanks to default binding modes, so name.clone() is cheap-ish and name.as_str() avoids the allocation entirely when the caller can borrow. Writing match *s forces the move and produces exactly the error in the introduction.
5. Iterating by reference instead of by value
let items = vec![String::from("a"), String::from("b")];
for s in &items { println!("{s}"); } // borrow, items still usable
let owned: Vec<String> = items.into_iter().collect(); // consume deliberatelyfor s in items in a helper that then returns a field of the collection is the same mistake at one remove: the loop consumed the vec, and the later use fails with E0382 rather than E0507.
6. Drop types are stricter
struct Frame { data: Vec<u8> }
impl Drop for Frame { fn drop(&mut self) {} }
fn bad(f: &mut Frame) -> Vec<u8> {
f.data // E0509: cannot move out of a Drop type
}A type with a Drop implementation is never allowed to be partially moved, because the destructor expects every field to be valid. Option<T> plus take is the standard escape hatch, and it is why so many structs in real code store Option<Handle> rather than Handle.
Common Compilation/Runtime Mistakes & Version Gotchas
Cloning to silence the checker everywhere. A clone() in a getter compiles and hides an API design problem: every caller pays an allocation. Prefer &T, then Cow, then clone as a last resort — and when you do clone, it should be because the caller genuinely stores the value.
Deriving Copy on a struct with a String. E0204 says the type has a destructor and cannot be Copy. Replacing the String with &'a str makes Copy possible and moves the lifetime problem to the struct definition, which is usually the right trade for small value types.
Boxing to avoid the move. Box<String> changes the field's type and still cannot be moved out of a shared reference; it only changes which error appears. Rc/Arc solve it by making the clone cheap, at the cost of shared mutability rules.
Version differences. Rust 2024 changed the drop order of if let temporaries, so a match that used to hold a borrow across an arm now drops earlier — usually silencing borrow errors, occasionally surfacing a new one. let ... else (1.65) removes the need for a moving match in guards. Rust 1.90 moved the default linker to rust-lld on Linux, which affects linking of tooling rather than borrow errors but is a common surprise in the same upgrade window.
Reading the suggestion the compiler prints. The note under E0507 usually offers the exact fix (consider borrowing here: &self.value). Apply the suggestion as a starting point and then decide whether the clone it suggests is the right cost; rustc --explain E0507 prints the canonical examples offline.
Comparing before and after a refactor. A signature change that fixes one call site often breaks another; cargo check --message-format short gives one line per error, which diffs cleanly with the text diff tool. When a large struct dump is involved, the regular expression tester is quicker than scrolling for the field name that the error says cannot move.
Reference material: Rust error code E0507 and References and Borrowing.
Official references
primary documentationThe Rust documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust E0282: type annotations needed
E0282 means inference ran out of information. Annotate the binding, add a turbofish to collect or parse, or fix the signature the value flows into.
Rust E0463: can't find crate for std
The target triple has no standard library installed. Add the target with rustup, check the target string and link the right ABI.
Rust E0432: unresolved import
E0432 is a module graph problem: a missing mod declaration, a private parent or a wrong path. Fix the tree, not the dependency list.
Rust E0106: missing lifetime specifier
E0106 appears when a returned borrow has no input to borrow from. Name the lifetime in functions, structs and impls, or return owned data.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.