Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readRust
#Rust#Ownership#Compiler Errors#Borrowing
A Rust value crate sliding from one owner slot to another, an amber moved tag and a cyan borrow key

Introduction & Quick Summary

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

The 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/Arc if 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 lineMeaningDirection
value moved hereOwnership left the bindingBorrow or clone at this site
value borrowed here after moveLater use of the old nameRemove or restructure the later use
cannot move out of ... which is behind a shared referenceMove attempted through &Use clone or mem::take
use of moved value inside a loopEach iteration consumed itIterate 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:

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

rust
// 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:

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

Change the signature to fn name(&self) -> &str when the caller still needs the struct.

Key Comparison Table

ApproachAllocationOwnershipUse when
&valueNoneUnchangedRead-only use
&mut valueNoneUnchangedMutation without transfer
value.clone()Deep copyNew ownerNeed two independent values
Copy typeNoneDuplicatedSmall plain data
Rc<T>Heap + countShared, immutableSingle-thread sharing
Arc<T>Heap + atomic countShared across threadsConcurrent sharing
mem::take(&mut v)NoneLeaves DefaultExtract from a field
std::mem::replaceNoneSwaps in new valueState machine transitions
Code shapeCommon E0382Preferred fix
fn f(s: String) called then s usedMove into functionTake &str
for x in vec then vec.len()Into-iterator consumesfor x in &vec
match opt { Some(s) => ... } then use optPartial moveMatch on &opt
move closure, then s usedClosure captured by valueClone before, or Arc
Struct field moved out, struct usedPartial moveDestructure with ..
Method fn f(self) then reuseConsuming method&self method

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Case 1: Function takes String but only reads it

rust
fn normalize(s: String) -> String { s.trim().to_lowercase() } let name = String::from(" API "); let fixed = normalize(name); println!("{}", name); // E0382

Take the cheapest type that expresses the requirement:

rust
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

rust
let users = vec![String::from("a"), String::from("b")]; for u in users { println!("{}", u); } println!("{}", users.len()); // E0382: users moved

for u in users calls into_iter(), which consumes the vector. Iterate by reference when the collection is needed afterwards:

rust
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

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

After a partial move the struct cannot be used as a whole. Either destructure deliberately:

rust
let Order { id, items, note } = order; consume(id, items, note);

or borrow the field and clone only when the value must outlive the struct:

rust
let items = order.items.clone(); drop_order(order); consume(items);

mem::take is the zero-allocation version when the field's type implements Default:

rust
let items = std::mem::take(&mut order.items); // order.items becomes empty drop_order(order);

Case 4: A move closure captures what it needs

rust
let prefix = String::from("user:"); let make = move |id: u64| format!("{}{}", prefix, id); println!("{}", prefix); // E0382

The closure took ownership of prefix. Either let it borrow:

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

rust
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

rust
let maybe = Some(String::from("x")); match maybe { Some(s) => println!("{}", s), None => {} } println!("{:?}", maybe); // E0382

Match on a reference to keep the original:

rust
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

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

rust
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.
  • Copy derive on a struct with a String. #[derive(Copy)] fails with E0204 because String is not Copy. Remove the String field, store an index or &'static str, or drop Copy.
  • Edition 2024 temporary scope. if let and 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 move blocks. A future marked move takes ownership of everything it touches, so a later use of the captured variable fails. Clone the Arc before 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.toml edition 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 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.