Learn/Rust/14. Ownership and borrowing
Lesson 14 of 15
Sign in

Rust, lesson 14

Ownership and borrowing

Rust manages memory without a garbage collector and without manual free calls. It does that with a set of ownership rules the compiler checks before your program runs. Once they click, you will see them in every Rust program, and many bugs common in other languages simply cannot happen.

The three rules

  1. Every value has exactly one owner, a variable.
  2. When the owner goes out of scope, the value is dropped (its memory is freed).
  3. Ownership can be moved to another variable, after which the old one cannot be used.

Why move instead of copy? A String owns a buffer on the heap. If a and b both owned it, both would try to free it at the end of the scope. Moving keeps exactly one owner.

Passing a value to a function moves it too:

Copy and Clone

2 exercises to try what you just read.

Exercise 1

Longest word

Press Ctrl Enter or Check to test your code.

Exercise 2

Playlist queue

Press Ctrl Enter or Check to test your code.

Small, simple types such as integers, floats, bool, char and tuples of them are Copy: assigning them makes a cheap bit-for-bit copy and the original stays usable. That is why let y = x; with numbers never caused trouble.

For other types, ask for a deep copy explicitly with .clone(). Cloning is honest about its cost; you can see every place your program duplicates data.

Borrowing with references

Moving everything around would be clumsy. Usually a function only needs to look at a value. A reference lets it borrow the value without taking ownership. Create one with &:

To let a function change a value, lend it mutably with &mut:

The borrowing rule

At any moment you may have either any number of shared references (&T) or exactly one mutable reference (&mut T), but not both. This prevents data races and bugs such as changing a vector while another part of the code is iterating over it:

The compiler tracks where each reference is last used, so a borrow ends as soon as you stop using it, not at the end of the block.

Slices

A slice is a reference to part of a collection: &str for strings and &[T] for arrays and vectors. Prefer them in parameters: fn total(prices: &[u32]) accepts a borrowed Vec, an array, or part of either. A function can also return a slice of its input:

The returned &str points into text, so the compiler makes sure text lives at least as long as the result. That link is a lifetime. Here Rust infers it; in more complex signatures you write it as 'a.

Putting it to work

A good default when designing functions:

  • Take &T (or &str, &[T]) when you only read.
  • Take &mut T when you change something in place.
  • Take T by value when the function keeps the value, for example storing it in a struct or a collection.

Further reading

  • The Rust Book: What is ownership?
  • The Rust Book: References and borrowing
  • The Rust Book: The slice type
  • The Rust Book: Validating references with lifetimes

Write fn longest(text: &str) -> &str that returns a slice of the input holding its longest word (words are separated by whitespace; on a tie, the first one wins; for a line with no words return an empty slice). It must not allocate a new String.

For each input line, print the longest word and its length in bytes as <word> (<len>), or - for a line with no words.

Sample input:

Sample output:

Manage a playlist stored in a Vec<String> owned by main. Write three functions with these exact signatures and use them:

  • fn add(queue: &mut Vec<String>, song: String) takes ownership of the song and appends it.
  • fn play(queue: &mut Vec<String>) -> Option<String> removes the first song and gives ownership of it back to the caller (or None if the queue is empty).
  • fn show(queue: &[String]) -> String only borrows the queue and returns queue: a, b, c, or queue: empty.

Each input line is a command: add <song title> (the title may contain spaces), play or list. For play, print playing <title> or nothing to play. For list, print show's result. The starter already parses commands; line.strip_prefix("add ") returns Some(rest) when the line starts with add .

Sample input:

Sample output:

let a = String::from("tea");
let b = a;              // ownership moves from a to b
// println!("{a}");     // error: value borrowed here after move
println!("{b}");
fn consume(s: String) {
    println!("{s}");
} // s is dropped here

let drink = String::from("coffee");
consume(drink);
// drink can no longer be used
let a = String::from("tea");
let b = a.clone(); // both are usable
fn length(s: &String) -> usize {
    s.len()
}

let name = String::from("Ferris");
let n = length(&name); // lend name
println!("{name} has {n} bytes"); // name is still ours
fn add_sugar(drink: &mut String) {
    drink.push_str(" with sugar");
}

let mut order = String::from("tea");
add_sugar(&mut order);
let mut v = vec![1, 2, 3];
let first = &v[0];
// v.push(4);          // error: cannot borrow v as mutable, it is also borrowed
println!("{first}");
v.push(4);             // fine: first is no longer used
fn first_word(text: &str) -> &str {
    text.split_whitespace().next().unwrap_or("")
}
the quick brown fox
a bb cc
quick (5)
bb (2)
add Blue Sky
add Rainy Day
list
play
play
play
list
queue: Blue Sky, Rainy Day
playing Blue Sky
playing Rainy Day
nothing to play
queue: empty