9 / 35

Core Rust Concepts· 13 min read· Lesson 9 of 35

Borrowing and References

Part 1 · Rust. Lend values without giving them away: learn & and &mut, the two borrowing rules, and how to read borrow-checker errors calmly.

In the last lesson, passing a String to a function moved it, and we lost access to it. That’s like handing a customer’s order ticket to another barista every time they only need to read it. In real life you’d just let them look. Rust has the same idea, and it’s called borrowing.

What is a reference?

A reference is a way to point at a value without owning it. You make one with the & symbol. We say the function borrows the value.

Café analogy: the menu board. Anyone can look at it, many people at once, but nobody takes it home. The café still owns it.

src/main.rs
fn print_order(drink: &String) {
println!("Order up: {drink}");
}
fn main() {
let drink = String::from("Iced Latte");
print_order(&drink);
print_order(&drink);
println!("Still mine: {drink}");
}
Output
Order up: Iced Latte
Order up: Iced Latte
Still mine: Iced Latte

Step by step:

  1. &drink creates a reference to drink. It doesn’t move ownership.
  2. The parameter type &String means “a reference to a String”.
  3. When print_order ends, the reference goes away, but the String itself is not dropped, because the function never owned it.
  4. Back in main, drink is still ours, so we can use it again.

Tip

Read & out loud as “a reference to” or “borrow”. &String is “a reference to a String”, and &drink is “borrow drink”.

Mutable references: &mut

A normal reference (&) is read-only. If you try to change the value through it, Rust refuses. To borrow something and change it, you need a mutable reference, written &mut.

src/main.rs
fn add_oat_milk(drink: &mut String) {
drink.push_str(" with oat milk");
}
fn main() {
let mut drink = String::from("Latte");
add_oat_milk(&mut drink);
println!("{drink}");
}
Output
Latte with oat milk
  1. The variable must be declared let mut. You can’t lend something out for changes if it isn’t changeable in the first place.
  2. &mut drink creates a mutable borrow.
  3. The parameter type &mut String says “I’m borrowing this String and I may change it”.
  4. push_str adds text to the end of the String.
  5. After the function returns, main owns the updated value.

It works the same for numbers:

src/main.rs
fn apply_discount(price_cents: &mut u32, discount_cents: u32) {
*price_cents -= discount_cents;
}
fn main() {
let mut price_cents: u32 = 500;
apply_discount(&mut price_cents, 50);
println!("New price: {price_cents} cents");
}
Output
New price: 450 cents

The new piece here is *price_cents. The * is called dereferencing: “follow the reference to the actual value”. For push_str above we didn’t need it, because method calls with a dot follow references automatically. For plain operators like -= on a number, you write the *.

The two borrowing rules

Here’s the heart of the lesson. At any moment, for a given value, you can have either:

  1. any number of read-only references (&), or
  2. exactly one mutable reference (&mut).

Never both at the same time. And a second rule:

  • References must always be valid. A reference can never outlive the value it points to.

Café analogy: lots of customers can read the menu board at once. But when the manager is rewriting the board with a marker, nobody else should be reading it halfway through the change, and only one person holds the marker. That’s exactly what Rust enforces.

Why so strict? These rules prevent a data race, a bug where one part of a program changes data while another part is reading it, giving weird, unpredictable results. Rust catches it before your program ever runs.

When the compiler stops you

Let’s break the rules on purpose and read the error together.

src/main.rs
fn main() {
let mut special = String::from("Pumpkin Spice");
let reader = &special;
let writer = &mut special;
writer.push_str(" Latte");
println!("{reader}");
}
Output
error[E0502]: cannot borrow `special` as mutable because it is also borrowed as immutable
--> src/main.rs:5:18
|
4 | let reader = &special;
| -------- immutable borrow occurs here
5 | let writer = &mut special;
| ^^^^^^^^^^^^ mutable borrow occurs here
...
8 | println!("{reader}");
| ------ immutable borrow later used here

Reading it from top to bottom:

  1. Headline: you tried a mutable borrow while a read-only borrow was alive.
  2. Line 4: where the read-only borrow (reader) started.
  3. Line 5: where you tried the mutable borrow. The ^^^^ marks the actual problem.
  4. Line 8: why the read-only borrow was still alive: you use reader later.

The fix is usually to change the order, so the borrows don’t overlap:

src/main.rs
fn main() {
let mut special = String::from("Pumpkin Spice");
let reader = &special;
println!("{reader}"); // last use of reader
let writer = &mut special;
writer.push_str(" Latte");
println!("{special}");
}
Output
Pumpkin Spice
Pumpkin Spice Latte

A borrow only lasts until its last use, not until the end of the block. After println!("{reader}"), reader is finished, so the mutable borrow is allowed.

Important

The borrow checker is the part of the compiler that checks these rules. When it complains, it isn’t saying you’re a bad programmer. It found a real situation where data could be read and changed at the same time. Usually the fix is moving a line up or down, or ending a borrow sooner.

Dangling references: Rust won’t let them happen

A dangling reference points at memory that has already been cleaned up. Imagine a sticky note saying “the muffins are on shelf 3” after the muffins were thrown away.

src/main.rs
fn todays_special() -> &String {
let special = String::from("Hazelnut Mocha");
&special
} // special is dropped here, so the reference would point at nothing

Rust refuses to compile this:

Output
error[E0106]: missing lifetime specifier
--> src/main.rs:1:24
|
1 | fn todays_special() -> &String {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
|
1 | fn todays_special() -> &'static String {
| +++++++
help: instead, you are more likely to want to return an owned value
|
1 - fn todays_special() -> &String {
1 + fn todays_special() -> String {
|

Lifetimes are an advanced topic, so don’t worry about the first help suggestion. The important line is “there is no value for it to be borrowed from”: the value dies at the end of the function, so you can’t hand out a reference to it. The last help gives the fix: return the owned String itself:

src/main.rs
fn todays_special() -> String {
String::from("Hazelnut Mocha")
}
fn main() {
let special = todays_special();
println!("Today's special: {special}");
}

Note

Later you’ll sometimes see lifetimes written inside type signatures, like 'a or '_. For example, Laravel Rust migrations use a type written AnyTransaction<'_>. You don’t need to write these yourself yet. It’s fine to read '_ as “the compiler works out how long this borrow lasts” and move on.

A friendlier parameter type: &str

You’ll often see functions take &str instead of &String. &str is a string slice, a borrowed view of some text. A &String converts to &str automatically, and text in quotes like "Espresso" already is a &str. That means a function taking &str accepts both:

src/main.rs
fn greet(name: &str) {
println!("Hi {name}, welcome to Rusty Bean!");
}
fn main() {
let regular = String::from("Sam");
greet(&regular);
greet("New customer");
}
Output
Hi Sam, welcome to Rusty Bean!
Hi New customer, welcome to Rusty Bean!

We’ll look at String vs &str more closely in Collections.

Warning

A common beginner mistake is forgetting mut in one of the three places. For a mutable borrow you need all three: let mut x, &mut x when calling, and &mut Type in the function’s parameter.

Try it yourself

  1. Write a function count_letters(name: &str) -> usize that returns name.len(). Call it twice with the same String from main, then print the String at the end to prove you still own it.
Show solution
fn count_letters(name: &str) -> usize {
name.len()
}
fn main() {
let drink = String::from("Cortado");
println!("{}", count_letters(&drink));
println!("{}", count_letters(&drink));
println!("Still have: {drink}");
}
  1. Write add_stock(beans_kg: &mut u32, delivered: u32) that adds a delivery to the café’s coffee bean stock. Start at 12 kg, add a 5 kg delivery, and print the result.
Show solution
fn add_stock(beans_kg: &mut u32, delivered: u32) {
*beans_kg += delivered;
}
fn main() {
let mut beans_kg: u32 = 12;
add_stock(&mut beans_kg, 5);
println!("Beans in stock: {beans_kg} kg");
}
Output
Beans in stock: 17 kg

Recap

  • &value borrows a value read-only. Ownership stays where it was.
  • &mut value borrows it mutably, so the function can change it. The variable must be let mut.
  • Rules: many & borrows or one &mut borrow, never both at once. References must always be valid.
  • A borrow ends at its last use, so reordering lines often fixes borrow errors.
  • Prefer &str for text parameters. It accepts both &String and string literals.

What’s next

Now that you can pass data around safely, let’s group related data together. Head to Structs to model the café’s menu items.

0 of 35 lessons complete

Search lessons

Type to search all lessons.