Sub topic 1
Why Borrowing Exists: Ownership and Moves
Prerequisites
This chapter assumes you already know:
- Basic Rust syntax: variables, functions, structs, and
println!. - How
String,Vec, and&strare used at a basic level. - The difference between stack and heap memory.
- How to build and run a program with
cargo.
The ownership rules
Rust manages memory without a garbage collector. It does this with three rules:
- Every value has exactly one owner.
- There is only one owner at a time.
- When the owner goes out of scope, the value is dropped and its memory is freed.
These rules let the compiler decide where to free memory, so there is no runtime cost. They also create a problem, which borrowing solves later in this tutorial.
What a move does
A String is a small struct on the stack with a pointer, a length, and a capacity. The text itself lives in a heap buffer. Assigning a String to another variable copies those three stack fields. It does not copy the heap buffer.
fn main() {
let a = String::from("hello");
let b = a;
println!("{b}");
}If both a and b stayed valid, both would try to free the same buffer when they went out of scope. That is a double free. Rust prevents it by treating let b = a; as a move. Ownership passes to b, and a can no longer be used.
fn main() {
let a = String::from("hello");
let b = a;
println!("{a} {b}");
}This program does not compile. The compiler reports E0382, "borrow of moved value: a".
Types such as integers, bool, and char implement the Copy trait. They live entirely on the stack, so assignment duplicates them and the original stays valid. String and Vec do not implement Copy.
Moves into functions
Passing a value to a function is also a move. The parameter becomes the new owner.
fn consume(s: String) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let n = consume(s);
println!("{n}");
// Using `s` here would be error E0382: the value moved into `consume`.
}The String is dropped when consume returns. If main still needs the text, you have two options without references. You can return the value from the function:
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}");
}Or you can call .clone() before passing the value, which allocates a second heap buffer and copies the text.
Both options are clumsy. Returning values makes signatures noisy, and cloning wastes memory and time. Most functions only need to read or briefly change a value, not own it.
Borrowing as the answer
A borrow is a reference to a value. The function uses the value, and the owner stays the owner. When the function finishes, nothing is dropped, because the function never owned the data.
Borrowing needs rules. If any code could hold a reference to a value while the owner freed or changed it, the reference would point at invalid memory. The next chapters cover the rules the compiler enforces to prevent this. They also show how Rust prevents data races and dangling pointers at compile time.
Exercise
Why does let b = a; make a unusable when a is a String, but not when a is an i32?
Show answer
A String owns a heap buffer, and copying only its stack fields would leave two owners that would both free the buffer. Rust moves ownership to b and invalidates a. An i32 implements Copy and lives entirely on the stack, so assignment duplicates it and both variables stay valid.
Exercise
A function fn print_len(s: String) is called as print_len(name), and name is used afterwards. What error does this cause, and what are two fixes that do not use references?
Show answer
The compiler reports E0382 because name was moved into the function. You can pass name.clone() so the caller keeps the original, or change the function to return the String so the caller can take ownership back.