Rust E0382: borrow of moved value and how to fix it
Ownership left the binding at an earlier line. Borrow instead of moving, clone when two owners are real, or destructure the struct before moving a field.

Introduction & Quick Summary
error[E0382]: borrow of moved value: `config`
--> src/main.rs:12:24
|
8 | let snapshot = config;
| ------ value moved here
...
12 | println!("{}", config.name);
| ^^^^^^^^^^^ value borrowed here after move
|
= note: move occurs because `config` has type `Config`, which does not implement the `Copy` traitThe compiler is reporting a use-after-move. Ownership transferred to another binding, function, closure or container at the line marked "value moved here", so the original name no longer refers to a live value. Rust rejects it at compile time rather than leaving a dangling reference, which is the whole point of the ownership model.
The fix depends on what the second use actually needs:
- Read-only access — borrow with
&instead of moving. - Two independent owners —
clone()if the type is cheap enough,Rc/Arcif it is shared and large. - Partial use of a struct — destructure, or move the fields individually.
- Value needed after a loop or closure — capture by reference, or clone once before the move.
| Diagnostic line | Meaning | Direction |
|---|---|---|
value moved here | Ownership left the binding | Borrow or clone at this site |
value borrowed here after move | Later use of the old name | Remove or restructure the later use |
cannot move out of ... which is behind a shared reference | Move attempted through & | Use clone or mem::take |
use of moved value inside a loop | Each iteration consumed it | Iterate by reference |
Core Mechanics, Signatures & Reproducible Setup
Every value has exactly one owner, and ownership ends at a move: a bitwise copy plus invalidation of the source, free for any size. Types implementing Copy are duplicated instead, so they never produce E0382.
Reproduce the canonical case:
#[derive(Debug)]
struct Config {
name: String,
retries: u32,
}
fn main() {
let config = Config { name: "api".into(), retries: 3 };
let snapshot = config; // move
println!("{:?}", config); // E0382
println!("{:?}", snapshot);
}Three minimal repairs, each with a different cost:
// 1. Borrow: no allocation, no ownership change
let snapshot = &config;
println!("{:?} {:?}", config, snapshot);
// 2. Clone: independent values, allocates the String
let snapshot = config.clone();
println!("{:?} {:?}", config, snapshot);
// 3. Move and never look back
let snapshot = config;
println!("{:?}", snapshot);Use cargo expand or cargo clippy to see where implicit moves happen; a method taking self by value is a move even when the call looks like a borrow:
impl Config {
fn into_name(self) -> String { self.name } // consumes the Config
}
let config = Config { name: "api".into(), retries: 3 };
let name = config.into_name();
// config is gone hereChange the signature to fn name(&self) -> &str when the caller still needs the struct.
Key Comparison Table
| Approach | Allocation | Ownership | Use when |
|---|---|---|---|
&value | None | Unchanged | Read-only use |
&mut value | None | Unchanged | Mutation without transfer |
value.clone() | Deep copy | New owner | Need two independent values |
Copy type | None | Duplicated | Small plain data |
Rc<T> | Heap + count | Shared, immutable | Single-thread sharing |
Arc<T> | Heap + atomic count | Shared across threads | Concurrent sharing |
mem::take(&mut v) | None | Leaves Default | Extract from a field |
std::mem::replace | None | Swaps in new value | State machine transitions |
| Code shape | Common E0382 | Preferred fix |
|---|---|---|
fn f(s: String) called then s used | Move into function | Take &str |
for x in vec then vec.len() | Into-iterator consumes | for x in &vec |
match opt { Some(s) => ... } then use opt | Partial move | Match on &opt |
move closure, then s used | Closure captured by value | Clone before, or Arc |
| Struct field moved out, struct used | Partial move | Destructure with .. |
Method fn f(self) then reuse | Consuming method | &self method |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: Function takes String but only reads it
fn normalize(s: String) -> String {
s.trim().to_lowercase()
}
let name = String::from(" API ");
let fixed = normalize(name);
println!("{}", name); // E0382Take the cheapest type that expresses the requirement:
fn normalize(s: &str) -> String {
s.trim().to_lowercase()
}
let name = String::from(" API ");
let fixed = normalize(&name);
println!("{} {}", name, fixed); // both usable&String coerces to &str, so callers only add &. Returning a new String is correct because lowercasing allocates.
Case 2: Moving a collection in a loop
let users = vec![String::from("a"), String::from("b")];
for u in users {
println!("{}", u);
}
println!("{}", users.len()); // E0382: users movedfor u in users calls into_iter(), which consumes the vector. Iterate by reference when the collection is needed afterwards:
for u in &users {
println!("{}", u); // u: &String
}
println!("{}", users.len());
for u in users.iter().cloned() { // explicit clone per item
consume(u);
}users.iter().copied() works only for Copy items; cloned() is the general form. If the loop is the last use, the original move is the correct and fastest choice.
Case 3: Partial move out of a struct
struct Order { id: u64, items: Vec<String>, note: Option<String> }
let order = Order { id: 1, items: vec![], note: None };
let items = order.items; // partial move
println!("{}", order.id); // fine: Copy field
println!("{:?}", order.note); // fine: different field
drop_order(order); // E0382: order partially movedAfter a partial move the struct cannot be used as a whole. Either destructure deliberately:
let Order { id, items, note } = order;
consume(id, items, note);or borrow the field and clone only when the value must outlive the struct:
let items = order.items.clone();
drop_order(order);
consume(items);mem::take is the zero-allocation version when the field's type implements Default:
let items = std::mem::take(&mut order.items); // order.items becomes empty
drop_order(order);Case 4: A move closure captures what it needs
let prefix = String::from("user:");
let make = move |id: u64| format!("{}{}", prefix, id);
println!("{}", prefix); // E0382The closure took ownership of prefix. Either let it borrow:
let make = |id: u64| format!("{}{}", prefix, id);
println!("{}", make(1));
println!("{}", prefix);or share it when the closure must outlive the current scope, such as a thread:
let prefix = std::sync::Arc::new(String::from("user:"));
let p = Arc::clone(&prefix);
let handle = std::thread::spawn(move || format!("{}{}", p, 1));
handle.join().unwrap();
println!("{}", prefix);Edition 2021 improved closure capture precision: a closure that only reads config.name captures that field, not the whole config. That helps with disjoint fields but still moves the field it reads when the closure is move.
Case 5: match on an owned Option
let maybe = Some(String::from("x"));
match maybe {
Some(s) => println!("{}", s),
None => {}
}
println!("{:?}", maybe); // E0382Match on a reference to keep the original:
match &maybe {
Some(s) => println!("{}", s),
None => {}
}
println!("{:?}", maybe);The same pattern applies to if let Some(s) = maybe combined with later use. When only one branch consumes the value, use as_ref() or as_deref() instead of restructuring the control flow.
Case 6: Returning a value borrowed from a local
fn make() -> &str {
let s = String::from("hello");
&s // E0515, often alongside E0382 in callers
}A local cannot be borrowed past its scope. Return the owned value, or a Cow when either borrowed or owned input is acceptable:
use std::borrow::Cow;
fn label(input: Option<&str>) -> Cow<'_, str> {
match input {
Some(s) => Cow::Borrowed(s),
None => Cow::Owned(String::from("default")),
}
}Cow avoids the clone in the common path while allowing an owned result.
Common Compilation/Runtime Mistakes & Version Gotchas
- Cloning to silence the compiler. It compiles and costs an allocation at every call site. Borrow first; clone only when two owners are genuinely required.
Copyderive on a struct with aString.#[derive(Copy)]fails with E0204 becauseStringis notCopy. Remove theStringfield, store an index or&'static str, or dropCopy.- Edition 2024 temporary scope.
if letand tail expressions drop temporaries earlier than in 2021, which turns some borrows that used to compile into E0382 or E0597. This is a semantic change, not a compiler regression. - NLL does not mean no moves. Non-lexical lifetimes shorten borrows, but a move still ends the value's life at the move site; the borrow checker is not being conservative.
async moveblocks. A future markedmovetakes ownership of everything it touches, so a later use of the captured variable fails. Clone theArcbefore the block, not inside it after the move.- Debug builds versus release. E0382 is always a compile error, so it cannot appear only in release. If a build "suddenly" fails, an edition bump or a dependency's MSRV change altered inference; check
Cargo.tomledition first.
When a refactor changes ownership, compare the old and new signatures with the diff tool to see which parameter changed from T to &T. For logs from a Rust service that prints owned values, the JSON formatter helps confirm the serialized shape before changing the struct.
Primary references: E0382 documents move semantics, borrowing and clone for this error, and ownership explains the stack/heap model underneath it.
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.