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.

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
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());
}// 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":
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 / operation | What happens | Original usable after | Cost |
|---|---|---|---|
Move (default for String, Vec, Box) | Ownership transfers | No | Free |
Copy (i32, f64, bool, &T, [T; N] of Copy) | Bitwise copy | Yes | Free |
Clone | Explicit duplicate | Yes | Allocation for heap types |
&T shared borrow | Read-only access | Yes | Free |
&mut T exclusive borrow | Read-write, no aliasing | Only after the borrow ends | Free |
Rc<T> / Arc<T> | Shared ownership, refcounted | Yes (each handle) | Refcount updates |
| Borrow combination | Allowed |
|---|---|
Many &T | Yes |
One &mut T | Yes |
&T and &mut T at the same time | No |
Two &mut T | No |
&T of one field and &mut T of another | Yes (disjoint fields, NLL) |
| Compiler error | Meaning | Usual fix |
|---|---|---|
E0382 use of moved value | Ownership already transferred | clone(), or borrow instead |
E0499 two mutable borrows | Aliasing &mut | Scope one borrow, use indices |
E0502 borrow while immutable borrow exists | Read + write overlap | Reorder, or copy the read value out |
E0505 cannot move out while borrowed | Move during an active borrow | End the borrow first |
E0507 cannot move out of borrowed content | Moving a field through & | clone(), std::mem::take, or match by reference |
E0716 temporary dropped while borrowed | Temporary dies too early | Bind to a let first |
Practical edge cases and deep dives
1. Mutating a collection while iterating it
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
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:
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.
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 behind4. Returning a reference to something you created
// 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.
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 Copy6. Closures capture by move when the type demands it
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
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 returnsA 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
| Error | Trigger | Fix |
|---|---|---|
E0382 borrow of moved value | Using a binding after a move | Borrow (&x) or clone() |
E0382 in a loop | Moving the same value each iteration | Move outside, or clone per iteration |
E0499 two mutable borrows | Second &mut while the first is live | Scope the first, or use indices |
E0502 read while mutably borrowed | v.push() during for x in &v | Collect first, apply after |
E0505 move while borrowed | Returning/dropping during a borrow | End the borrow before moving |
E0507 move out of borrowed content | let s = v[0]; | v[0].clone() or mem::take |
E0515 returns reference to local | Returning &local | Return the owned value |
E0716 temporary dropped while borrowed | let x = foo().iter(); | Bind the owner first |
E0716 from &format!(...) | Reference to a temporary | let s = format!(...); &s |
| "value was mutably borrowed here" in a closure | &mut captured by two closures | Refactor to one owner, or RefCell |
Trait bound Copy rejects String | Over-constrained generic | Relax to Clone |
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 Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.