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.
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}");}Order up: Iced LatteOrder up: Iced LatteStill mine: Iced LatteStep by step:
&drinkcreates a reference todrink. It doesn’t move ownership.- The parameter type
&Stringmeans “a reference to aString”. - When
print_orderends, the reference goes away, but theStringitself is not dropped, because the function never owned it. - Back in
main,drinkis 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.
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}");}Latte with oat milk- The variable must be declared
let mut. You can’t lend something out for changes if it isn’t changeable in the first place. &mut drinkcreates a mutable borrow.- The parameter type
&mut Stringsays “I’m borrowing this String and I may change it”. push_stradds text to the end of theString.- After the function returns,
mainowns the updated value.
It works the same for numbers:
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");}New price: 450 centsThe 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:
- any number of read-only references (
&), or - 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.
fn main() { let mut special = String::from("Pumpkin Spice");
let reader = &special; let writer = &mut special; writer.push_str(" Latte");
println!("{reader}");}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 here5 | let writer = &mut special; | ^^^^^^^^^^^^ mutable borrow occurs here...8 | println!("{reader}"); | ------ immutable borrow later used hereReading it from top to bottom:
- Headline: you tried a mutable borrow while a read-only borrow was alive.
- Line 4: where the read-only borrow (
reader) started. - Line 5: where you tried the mutable borrow. The
^^^^marks the actual problem. - Line 8: why the read-only borrow was still alive: you use
readerlater.
The fix is usually to change the order, so the borrows don’t overlap:
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}");}Pumpkin SpicePumpkin Spice LatteA 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.
fn todays_special() -> &String { let special = String::from("Hazelnut Mocha"); &special} // special is dropped here, so the reference would point at nothingRust refuses to compile this:
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 fromhelp: 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:
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:
fn greet(name: &str) { println!("Hi {name}, welcome to Rusty Bean!");}
fn main() { let regular = String::from("Sam"); greet(®ular); greet("New customer");}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
- Write a function
count_letters(name: &str) -> usizethat returnsname.len(). Call it twice with the sameStringfrommain, then print theStringat 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}");}- Write
add_stock(beans_kg: &mut u32, delivered: u32)that adds a delivery to the café’s coffee bean stock. Start at12kg, add a5kg 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");}Beans in stock: 17 kgRecap
&valueborrows a value read-only. Ownership stays where it was.&mut valueborrows it mutably, so the function can change it. The variable must belet mut.- Rules: many
&borrows or one&mutborrow, never both at once. References must always be valid. - A borrow ends at its last use, so reordering lines often fixes borrow errors.
- Prefer
&strfor text parameters. It accepts both&Stringand 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