Skip to content

Ownership and borrowing

Almost every language handles memory in one of two ways: the programmer frees it by hand (C, C++, with bugs that are hard to find) or a garbage collector frees it automatically (C#, Java, Python, at the cost of pauses and more memory). Rust uses a third: ownership rules that the compiler checks. If the program compiles, memory is freed at exactly the right moment and there are no accesses to memory that was already freed.

  1. Each value has one owner (a variable).
  2. There’s only one owner at a time.
  3. When the owner goes out of its { } block, the value is freed.
fn main() {
{
let greeting = String::from("hello"); // greeting owns the text
println!("{greeting}");
} // the block ends here: the text is freed by itself
}

When you assign a String to another variable, or pass it to a function, ownership moves:

fn print(text: String) {
println!("{text}");
} // text is freed here
fn main() {
let a = String::from("hello");
let b = a; // ownership goes from a to b
// println!("{a}"); // error: `a` no longer owns anything
print(b); // now it belongs to `print`
// println!("{b}"); // error: borrow of moved value: `b`
}

If you remove the //, Raxorin Studio underlines the line with error E0382 (borrow of moved value) and shows you where the value was moved.

If you really need two copies, use .clone(): let b = a.clone();. It’s explicit on purpose, because copying a long text or vector costs something.

Most of the time you don’t want to move the value, just lend it: the function uses it and gives it back.

fn length(text: &String) -> usize {
text.len()
} // the borrow ends; the text still belongs to whoever lent it
fn main() {
let name = String::from("Ann");
let n = length(&name); // &: lend
println!("{name} has {n} letters"); // name is still usable
}
fn add_exclamation(text: &mut String) {
text.push('!');
}
fn main() {
let mut greeting = String::from("Hello");
add_exclamation(&mut greeting);
println!("{greeting}"); // Hello!
}

The golden rule of borrowing:

At any given moment there can be many read borrows (&) or a single borrow to modify (&mut), never both at the same time.

fn main() {
let mut list = vec![1, 2, 3];
let first = &list[0]; // read borrow
// list.push(4); // error E0502: it can't be modified while it's borrowed
println!("{first}"); // `first` is last used here
list.push(4); // now it can
println!("{list:?}");
}

Why? push may move the vector to another part of memory if it needs more space, and first would be left pointing to old memory. In C++ that’s a hard-to-find bug; in Rust it doesn’t compile.

Now the difference makes sense:

  • String owns its text: it can grow, change, and it’s freed along with it.
  • &str is a borrow of a text (from a String, or from a fixed text in the program like "hello").

That’s why functions usually take &str: they accept any text without keeping it.

fn greet(name: &str) {
println!("Hello, {name}");
}
fn main() {
let owned = String::from("Ann");
greet(&owned); // a &String turns into &str by itself
greet("Luis"); // a fixed text is already a &str
}

Ownership errors are the most common when you start. Some typical ones:

Error What’s happening Typical fixes
E0382 use of moved value You use something that was already moved Borrow with & instead of moving, or .clone()
E0502 / E0499 cannot borrow A &mut borrow clashes with another Finish using one borrow before the next
E0106 missing lifetime specifier A function returns a borrow without saying where it comes from Return an owned value (String) instead of &str
E0596 cannot borrow as mutable mut is missing let mut

Read the help: line of the message: it almost always says what to change. And don’t worry about “fighting the compiler” at first: every error it shows you is a bug that won’t reach your program.

Next: Structs, enums and match.