Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readRust
#rust#e0507#ownership#borrow-checker
Bold white headline reading CANNOT MOVE with a Rust crate showing an amber value block chained to a cyan shared reference plate.

Introduction & Quick Summary

The borrow checker rejects a move through a reference:

code
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` trait

You 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.

rust
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 Default

Most 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 &T copies primitive and Copy types and borrows everything else.
  • Producing an owned T from a &T requires either Clone (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, and mem::replace provide.

Reproduce the error and its neighbours in one file:

rust
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 siteCompiler seesWhat to change
a getter returning a field&selfborrow, or clone deliberately
match *s on a borrowed enumshared referencematch s and bind by reference
for x in vec then use vecmove of the collectionfor x in &vec
a field of a Drop typepartial move forbiddenOption plus take

Key Comparison Table

Choosing the extraction shape:

IntentSignatureCostLeaves the source
read without copyingfn f(&self) -> &strnoneuntouched
return an owned copyfn f(&self) -> Stringone allocationuntouched
move out oncefn f(&mut self) -> Option<T>noneNone
move out, keep usablefn f(&mut self) -> T where T: DefaultnoneDefault::default()
share ownershipfn f(&self) -> Rc<T> / Arc<T>refcount bumpuntouched
avoid the clone lazilyfn f(&self) -> Cow<'_, str>none until mutationuntouched

Which adjacent error you might be looking at:

ErrorMeaningTypical fix
E0507move out of a shared referenceborrow, clone, or take
E0509move out of a type that implements Dropmem::take or Option
E0382use of a moved valueclone, borrow, or reorder
E0502 / E0499conflicting borrowsnarrow the borrow scope
E0515returning a reference to a temporaryreturn owned data
E0204Copy on a type with a destructoruse Clone instead

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Getters: borrow first, clone only when needed

rust
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

rust
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

rust
#[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

rust
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

rust
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 deliberately

for 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

rust
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 documentation

The Rust documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.