Sub topic 1
Why Borrowing Exists: Ownership and Moves
Rust frees memory without a garbage collector and without manual free calls. It does this by giving every value exactly one owner. That rule prevents a whole class of memory bugs, but on its own it makes ordinary code awkward. Borrowing is the feature that removes the awkwardness. This chapter shows the problem first, so the rest of the tutorial has a clear purpose.
Prerequisites
This chapter assumes you already have the following:
- Basic Rust syntax: variables, functions, structs, and
println!. - Familiarity with
String,Vec, and&str. - A basic idea of stack versus heap memory.
- The ability to build and run a program with
cargo.
You do not need to know anything about references or lifetimes yet. Those come in the next chapters.
The ownership rules
Rust's ownership model has three rules:
- Every value has exactly one owner, which is a variable (or a field, or an element of a collection).
- There is only one owner at a time.
- When the owner goes out of scope, the value is dropped and its resources are released.
Take a String. It is a small struct on the stack holding a pointer, a length, and a capacity. The text itself lives in a heap allocation. When the owning variable goes out of scope, Rust calls drop, which frees the heap allocation.
fn main() {
{
let s = String::from("hello");
println!("{s}");
} // s goes out of scope here, and its heap buffer is freed
}The compiler inserts the cleanup at the closing brace. There is no runtime cost for tracking this, because the owner is known at compile time.
Moves
What happens if two variables could own the same heap buffer? At scope end, both would try to free it. That is a double free, a classic memory-safety bug. Rust avoids it by making assignment of a non-Copy value a move. Ownership transfers, and the old variable becomes unusable.
fn main() {
let a = String::from("hello");
let b = a;
println!("{a}");
}This does not compile. The compiler reports error E0382, "borrow of moved value: a". After let b = a;, only b owns the buffer.
A move copies only the small stack part (pointer, length, capacity). It does not copy the heap data. So a move is cheap, and it is a bitwise copy followed by the compiler marking the source as invalid.
Types that are copied instead
Some types do not move. They implement the Copy trait, which means assignment duplicates the value and both variables stay valid. Integers, floats, bool, char, and tuples or arrays made only of Copy types are all Copy.
fn main() {
let x = 5;
let y = x;
println!("{x} {y}");
}A type can be Copy only if copying it bit for bit is safe. A String owns a heap buffer, so it cannot be Copy. Any type that implements Drop cannot be Copy either.
| Type | Copy or move | Reason |
|---|---|---|
| `i32`, `f64`, `bool`, `char` | Copy | Fixed size, no heap resource |
| `(i32, i32)` | Copy | All fields are `Copy` |
| `String`, `Vec<T>`, `Box<T>` | Move | Own a heap allocation |
| `(i32, String)` | Move | One field is not `Copy` |
| `&T` (shared reference) | Copy | Duplicating a pointer is safe |
The last row previews the next chapter: shared references are Copy, which is part of why they are so easy to pass around.
Moves into functions
Passing an argument to a function is also an assignment, so it moves too. This is where the cost of strict ownership becomes visible.
fn length(s: String) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let n = length(s);
println!("{s} has length {n}");
}This fails with E0382 again. The call length(s) moved s into the function. When length returns, its parameter goes out of scope and the buffer is dropped. The caller's s has nothing left to point to, so Rust forbids using it.
The function only wanted to read the string, but the caller lost it. One workaround is to hand ownership back through the return value.
fn length_and_back(s: String) -> (String, usize) {
let n = s.len();
(s, n)
}
fn main() {
let s = String::from("hello");
let (s, n) = length_and_back(s);
println!("{s} has length {n}");
}This compiles and is correct. It is also clumsy. Every function that merely inspects a value would need to return it. Return types get noisy, call sites need rebinding, and it gets worse with several arguments.
Borrowing as the answer
Borrowing lets a function use a value without owning it. Instead of passing the String, the caller passes a reference to it, written &s. The function declares the parameter as &String.
fn length(s: &String) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let n = length(&s);
println!("{s} has length {n}");
}Here main still owns s. The function receives a pointer to it and gives it back implicitly, because a reference does not own what it points to. When the function returns, only the reference goes away. The String is not dropped, because the reference never owned it.
The rest of the tutorial builds on this idea. The key point for now is that a move and a borrow answer different questions:
| Question | Move | Borrow |
|---|---|---|
| Who is responsible for freeing the value? | The new owner | The original owner, unchanged |
| Can the caller use the value afterwards? | No | Yes |
| What is passed? | The value itself | A pointer to the value |
| Typical use | Consuming or storing the value | Reading or temporarily modifying it |
Borrowing is not a loophole in ownership. The owner remains the only party that frees the value. The compiler checks that no reference outlives its owner, and later chapters cover how.
Cloning as a third option
If a function needs its own copy, you can duplicate the data explicitly with clone.
fn length(s: String) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let n = length(s.clone());
println!("{s} has length {n}");
}This compiles. clone allocates a new heap buffer and copies the text, so the function owns an independent value and s is untouched. The difference from a move is that the cost is visible in the source. You pay for an allocation and a copy of every byte.
Cloning is correct when you truly need two independent owners. It is a poor choice when you only want to read, because borrowing does the same job for free. A later chapter covers how to choose among the three.
Common mistakes
- Using a variable after passing it by value. Error E0382 usually means a move happened earlier. Look for a function call, a
letbinding, or aforloop over a collection that consumed the value. - Moving inside a loop. Calling
consume(s)in each iteration movesson the first pass. The compiler reports that the value was moved in the previous iteration of the loop. - Assuming a move copies data. It copies only the stack part, so a move of a huge
Vecis as cheap as a move of a small one. - Cloning to silence an error. A
.clone()that appears only to make E0382 disappear often hides a function that should take a reference.
What comes next
You now have the problem: ownership is strict, and passing by value consumes the value. The next chapter looks closely at shared references, &T, and how many of them can exist at once.
Exercise
The code below fails with E0382. Explain why, and give two different fixes, one that borrows and one that clones. fn shout(s: String) -> String { s.to_uppercase() } fn main() { let name = String::from("ferris"); let loud = shout(name); println!("{name} became {loud}"); }
Show answer
The call shout(name) moves name into the function, so name is invalid afterwards and the println! that uses it is rejected. Borrowing fix: change the parameter to s: &str (or &String), call shout(&name), and the function returns a new String while main keeps ownership of name. Cloning fix: call shout(name.clone()), which passes an independent copy and leaves name valid. Borrowing is preferable here because shout only reads its input.
Exercise
Which of these assignments leaves both variables usable: let b = a; where a is an i32, where a is a Vec<i32>, or where a is a (i32, String)? Say why for each.
Show answer
Only the i32 case. i32 is Copy, so the assignment duplicates the value and both variables stay valid. Vec<i32> owns a heap buffer and is not Copy, so the value moves and a becomes unusable. (i32, String) is not Copy because the String field is not Copy, so it moves as well.