Ch 4 — Understanding Ownership ⭐ (the most important chapter)
📖 https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html
The three ownership rules
- Each value has exactly one owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped (destructor runs, memory freed).
Moves vs copies
let s1 = String::from("hello");
let s2 = s1; // MOVE: s1 is now invalid (heap data not copied)
// println!("{s1}"); // ❌ compile error: value borrowed after move
let x = 5;
let y = x; // COPY: i32 is `Copy`, both remain valid
let s3 = s2.clone(); // deep copy, explicit and visible
- Types that are
Copy: all integers, floats,bool,char, tuples ofCopytypes, shared references&T. Anything with heap data / aDropimpl is not. - Passing a value to a function moves it (or copies if
Copy); returning moves ownership out.
References and borrowing
fn calculate_length(s: &String) -> usize { s.len() } // borrow, don't take ownership
let len = calculate_length(&s);
fn change(s: &mut String) { s.push_str(", world"); } // mutable borrow
change(&mut s);
The borrowing rules (enforced at compile time):
At any given time you may have either any number of immutable references (
&T) or exactly one mutable reference (&mut T) — never both. References must never outlive the data they point to.
let mut s = String::from("hi");
let r1 = &s;
let r2 = &s; // ✅ many shared borrows
// let r3 = &mut s; // ❌ can't mutably borrow while shared borrows are live
println!("{r1} {r2}");
let r3 = &mut s; // ✅ OK — r1/r2's last use was above (non-lexical lifetimes)
- Dangling references are impossible: returning
&local_varfrom a function is a compile error.
Slices
let s = String::from("hello world");
let hello: &str = &s[0..5]; // string slice — borrowed view
let word = s.split_whitespace().next().unwrap();
fn first_word(s: &str) -> &str { ... } // take &str, not &String — works for both
let a = [1, 2, 3, 4, 5];
let slice: &[i32] = &a[1..3]; // array/vec slice
&stris the type of string literals and string slices; prefer&strparameters over&String.- Slices are borrows, so the borrow rules apply — you can’t
s.clear()while a slice ofsis live.
Mental model (stack vs heap)
- A
Stringis a stack struct{ ptr, len, capacity }pointing to heap bytes. Move = copy the stack struct + invalidate the source. No garbage collector, no manualfree—Dropat scope end, deterministically.
Gotchas
- “Value borrowed after move” and “cannot borrow as mutable because it is also borrowed as immutable” are the two errors you’ll fight most — both are this chapter.
- Iterating
for x in vmoves the vector; usefor x in &vor&mut v. - The borrow checker tracks borrows to their last use, not end of scope (NLL) — code that looks illegal may compile fine.