Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust Ownership and Borrowing: Move Semantics and Borrow Checker Rules

One owner, either many readers or one writer. How moves differ from Copy, what NLL changed, and the four error codes that cover most borrow failures.

~4 min readRust
#Rust#Ownership#Memory Safety
3D illustration of a stack frame passing an owned heap pointer while borrow tags attach to the same data block

Quick Summary

Every value in Rust has exactly one owner, and when the owner goes out of scope the value is dropped. Assigning a non-Copy value to another binding moves it: the original binding becomes unusable, and the compiler enforces that at compile time rather than with a runtime check. Types that implement Copy (i32, f64, bool, char, shared references, and small tuples/arrays of those) are copied bit for bit instead, and the original stays valid.

Borrowing lets code read or write a value without taking ownership, under one rule: at any moment you may have either any number of shared references &T or exactly one mutable reference &mut T. That rule is what makes data races and iterator invalidation impossible without a garbage collector. The borrow checker (with non-lexical lifetimes since Rust 2018) tracks where a reference is actually used, so a borrow ends at its last use, not at the closing brace.

Almost every ownership error you will hit is one of three shapes: use of a moved value (E0382), two conflicting borrows (E0499/E0502), or a reference outliving its owner (E0597/E0515/E0716). Each has a small set of idiomatic fixes — pass a slice instead of a collection, take &mut instead of the value, collect indices before mutating, or return owned data instead of a reference into a local.

Basic syntax and query signatures

rust
fn main() { let s1 = String::from("hello"); let s2 = s1; // move: s1 is no longer usable // println!("{s1}"); // E0382: borrow of moved value let n1 = 5; let n2 = n1; // Copy: n1 is still usable println!("{n1} {n2}"); let s3 = s2.clone(); // explicit deep copy for heap data println!("{} {}", s2.len(), s3.len()); }
rust
// Taking ownership vs borrowing fn consume(s: String) -> usize { s.len() } // takes ownership fn inspect(s: &str) -> usize { s.len() } // borrows, accepts &String and &str fn mutate(s: &mut String) { s.push('!'); } fn main() { let mut s = String::from("abc"); let len = inspect(&s); // auto-deref &String -> &str mutate(&mut s); let owned = consume(s.clone()); let owned2 = consume(s); // last use: move is fine here println!("{len} {owned} {owned2}"); }

Borrows of fields and slices are the everyday tools that replace "pass the whole thing and clone":

rust
fn total(prices: &[u32]) -> u32 { prices.iter().sum() } fn first_word(s: &str) -> &str { s.split_whitespace().next().unwrap_or("") } struct Cart { items: Vec<Item>, discount: u32 } impl Cart { fn items(&self) -> &[Item] { &self.items } // shared borrow of one field fn apply(&mut self, code: u32) { self.discount = code; } }

Key comparison table

Trait / operationWhat happensOriginal usable afterCost
Move (default for String, Vec, Box)Ownership transfersNoFree
Copy (i32, f64, bool, &T, [T; N] of Copy)Bitwise copyYesFree
CloneExplicit duplicateYesAllocation for heap types
&T shared borrowRead-only accessYesFree
&mut T exclusive borrowRead-write, no aliasingOnly after the borrow endsFree
Rc<T> / Arc<T>Shared ownership, refcountedYes (each handle)Refcount updates
Borrow combinationAllowed
Many &TYes
One &mut TYes
&T and &mut T at the same timeNo
Two &mut TNo
&T of one field and &mut T of anotherYes (disjoint fields, NLL)
Compiler errorMeaningUsual fix
E0382 use of moved valueOwnership already transferredclone(), or borrow instead
E0499 two mutable borrowsAliasing &mutScope one borrow, use indices
E0502 borrow while immutable borrow existsRead + write overlapReorder, or copy the read value out
E0505 cannot move out while borrowedMove during an active borrowEnd the borrow first
E0507 cannot move out of borrowed contentMoving a field through &clone(), std::mem::take, or match by reference
E0716 temporary dropped while borrowedTemporary dies too earlyBind to a let first

Practical edge cases and deep dives

1. Mutating a collection while iterating it

rust
let mut v = vec![1, 2, 3]; // for x in &v { v.push(*x); } // E0502: immutable borrow in the loop // Fix A: collect the changes, apply after let additions: Vec<i32> = v.iter().map(|x| x * 2).collect(); v.extend(additions); // Fix B: build a new collection let doubled: Vec<i32> = v.iter().map(|x| x * 2).collect(); let v = doubled;

v.push inside for x in &v is the canonical error, but the deeper lesson is that "mutate while iterating" is a design smell in any language. Rust's refusal is a real bug report, not an inconvenience.

2. Splitting one mutable borrow into several

rust
fn split_first(v: &mut Vec<i32>) -> (&mut i32, &mut [i32]) { let (first, rest) = v.split_first_mut().unwrap(); (first, rest) } // Two independent mutable borrows of one slice, without unsafe let (a, b) = v.split_at_mut(2); // a: &mut [i32], b: &mut [i32]

Index-based loops work where borrows would alias, because the borrow ends before the next index:

rust
for i in 1..v.len() { v[i] += v[i - 1]; // two reads and one write, no live long borrow }

3. Partial moves out of a struct

A field can be moved out of a struct by value, and the rest of the struct stays usable as long as it does not implement Drop.

rust
struct Pair { name: String, age: u32 } let p = Pair { name: "a".into(), age: 3 }; let name = p.name; // partial move println!("{}", p.age); // OK: p is partially moved // println!("{}", p.name); // E0382 // For a type with Drop, borrowing is the only option: let v = vec![String::from("x")]; // let s = v[0]; // E0507: cannot move out of index let s = v[0].clone(); // copy the data out let s2 = std::mem::take(&mut v[0] as &mut String); // or leave a default behind

4. Returning a reference to something you created

rust
// fn make() -> &str { &String::from("hi") } // E0515: returns a value referencing local fn make() -> String { String::from("hi") } // return ownership // Storing a reference in a struct requires the caller to own the data struct Config<'a> { name: &'a str } fn cfg(name: &str) -> Config<'_> { Config { name } }

The rule reads clearly once you see it: a reference is a promise that someone else keeps the value alive. If no one does, return the value.

5. Copy versus Clone in generic code

T: Copy gives you implicit copies, T: Clone requires .clone(). Adding Copy to a generic bound makes the type no longer work with String, because String is not Copy — the most common API mistake in library code.

rust
fn dupe<T: Clone>(x: &T) -> T { x.clone() } // works for String and i32 fn needs_copy<T: Copy>(x: T) -> (T, T) { (x, x) } // Deriving Copy is only possible when every field is Copy #[derive(Clone, Copy)] struct Point { x: f64, y: f64 } // #[derive(Clone, Copy)] // struct Named { name: String } // error: String is not Copy

6. Closures capture by move when the type demands it

rust
let name = String::from("db"); let print = move || println!("{name}"); // takes ownership of name print(); print(); // Fn: can be called repeatedly // println!("{name}"); // E0382 // A thread that outlives the scope needs owned data or a scoped thread let handle = std::thread::spawn(move || name.len());

Without move, the closure borrows name and cannot be sent to another thread unless the borrow outlives it — which is exactly what std::thread::scope relaxes.

7. Borrowing in method chains and self by value

rust
impl Cart { fn add(mut self, item: Item) -> Self { self.items.push(item); self } // builder pattern fn len(&self) -> usize { self.items.len() } } let cart = Cart::default().add(item).add(item2).len(); // consumes and returns

A method that takes self by value cannot be called twice on the same binding. Confusing self, &self, and &mut self in an API is a design decision, not a syntax detail: taking &self keeps the caller able to reuse the value, taking self enables move-based builders that cannot be misused later.

Common mistakes and runtime errors

ErrorTriggerFix
E0382 borrow of moved valueUsing a binding after a moveBorrow (&x) or clone()
E0382 in a loopMoving the same value each iterationMove outside, or clone per iteration
E0499 two mutable borrowsSecond &mut while the first is liveScope the first, or use indices
E0502 read while mutably borrowedv.push() during for x in &vCollect first, apply after
E0505 move while borrowedReturning/dropping during a borrowEnd the borrow before moving
E0507 move out of borrowed contentlet s = v[0];v[0].clone() or mem::take
E0515 returns reference to localReturning &localReturn the owned value
E0716 temporary dropped while borrowedlet x = foo().iter();Bind the owner first
E0716 from &format!(...)Reference to a temporarylet s = format!(...); &s
"value was mutably borrowed here" in a closure&mut captured by two closuresRefactor to one owner, or RefCell
Trait bound Copy rejects StringOver-constrained genericRelax to Clone

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.