In the ownership lesson, the cashier at Rusdi's Pancake Stall handed the order slip to the kitchen, and the cashier no longer held it. Yet the kitchen often only needs to read the slip. The cashier can just show it: the kitchen reads, and the slip stays in the cashier's hand. The cashier, the kitchen and Sari, who placed the order, can all read the same slip at the same time. But while someone is writing an addition on the slip, nobody else may read or write, because they could misread half-written words.
In Rust, using a value without becoming its owner, the way the kitchen reads the cashier's slip, is called borrowing. You do it through a reference (also called a borrow): a pointer to a value that another variable owns, written with &. In code, the slip is a String named slip. Showing the slip so others can read it is &slip. Lending the pen so that one person can write an addition on the slip is &mut slip. The rule "many readers, or one writer" is the borrowing rule. You have already seen & in several earlier lessons, for example for p in &orders and &self. This lesson explains the rules behind it: when you may make a borrow, how many, and for how long.
&: borrowing to read
The program below lends slip to two functions, then still prints slip at the end:
fn length_of(s: &String) -> usize {
s.len()
}
fn cook(slip: &String) {
println!("Cooked: {}", slip);
}
fn main() {
let slip = String::from("2x sweet pancake");
let length = length_of(&slip);
cook(&slip);
println!("Cashier: {} ({} letters)", slip, length);
}
Cooked: 2x sweet pancake
Cashier: 2x sweet pancake (16 letters)
&slipmakes a reference toslip. The owner is stillslip. Only the pointer is sent, 8 bytes on a 64-bit computer.s: &Stringmeans this parameter borrows aString. Compare it withcook(slip: String)in the ownership lesson: there the parameter became the slip's new owner.- When
length_ofends,sleaves its scope, but nothing is dropped, because a borrower is not an owner. That is whyslipcan still be printed on the last line, with no E0382.
&mut: borrowing to change
This program changes two values that main owns, through &mut borrows: it adds text to slip and adds 5 to total.
fn add_item(slip: &mut String, item: &str) {
slip.push_str(item);
}
fn add_iced_tea(total: &mut u32) {
*total += 5;
}
fn main() {
let mut slip = String::from("2x sweet pancake");
let mut total: u32 = 102;
add_item(&mut slip, ", 1x iced tea");
add_iced_tea(&mut total);
println!("{}", slip);
println!("Total: {}", total);
}
2x sweet pancake, 1x iced tea
Total: 107
- Changing through a borrow needs
mutin three places: the variable (let mut slip), the borrow (&mut slip) and the parameter type (&mut String). - Inside
add_iced_tea,totalis a borrow, not the number itself.*totalmeans "the valuetotalpoints at". This*is called a dereference.*total += 5changesmain'stotalfrom 102 to 107. For methods, Rust adds the*itself, soslip.push_str(item)is enough. - If you forget
&mutin the call, as inadd_item(&slip, ...), the compiler refuses with E0308types differ in mutability. If you forgetlet mut, the compiler refuses with E0596cannot borrow `slip` as mutable, as it is not declared as mutable.
The rule: many readers, or one writer
At any one time, a value may have one of these:
- Any number of
&borrows, or - Exactly one
&mutborrow, and while that borrow is alive (it will still be used later), no other borrow.
In this code, cashier and kitchen both borrow slip to change it, and the compiler refuses:
fn main() {
let mut slip = String::from("2x sweet pancake");
let cashier = &mut slip;
let kitchen = &mut slip;
cashier.push_str(", 1x iced tea");
kitchen.push_str(", take-away");
println!("{}", slip);
}
error[E0499]: cannot borrow `slip` as mutable more than once at a time
--> src/main.rs:4:19
|
3 | let cashier = &mut slip;
| --------- first mutable borrow occurs here
4 | let kitchen = &mut slip;
| ^^^^^^^^^ second mutable borrow occurs here
5 | cashier.push_str(", 1x iced tea");
| ------- first borrow later used here
The borrow cashier is still used on line 5, so the borrow kitchen on line 4 is refused.
The owner must follow the rule too. While something borrows the value, the owner may not change it, not even when the value is just a u32. Suppose you write let cashier = &price; price = 35;, then use cashier again. The compiler refuses with E0506 cannot assign to `price` because it is borrowed.
Why the rule is so strict
In the code below, the cashier borrows the first order through first. Then a new order comes in with push. After that, the cashier prints first. Before you look at the result, guess: does the code compile?
fn main() {
let mut orders = vec![102, 70, 38];
let first = &orders[0];
orders.push(45);
println!("First: {}", first);
}
error[E0502]: cannot borrow `orders` as mutable because it is also borrowed as immutable
--> src/main.rs:4:5
|
3 | let first = &orders[0];
| ------ immutable borrow occurs here
4 | orders.push(45);
| ^^^^^^^^^^^^^^^ mutable borrow occurs here
5 | println!("First: {}", first);
| ----- immutable borrow later used here
It doesn't compile. push needs &mut orders (a borrow to change), while first is still borrowing to read. A vec![...] of 3 numbers has a capacity (the number of places already requested) of exactly 3. So on push, there is no room for a fourth number. The Vec requests new memory on the heap with capacity 6, moves the items there and gives the old memory back. When tried without first, the address of the items changed from 0x100dbded0 to 0x977000980. If the compiler allowed this code, first would point into the old memory that was already given back. A reference that points at memory already given back is called a dangling reference. In C++ this bug compiles, and then the running program reads garbage data or crashes. The "one writer" rule also keeps programs with many threads safe from a data race: two threads using the same data at the same time, while at least one of them writes to it.
A borrow ends at its last use
If you put the println! above the push, the program compiles:
fn main() {
let mut orders = vec![102, 70, 38];
let first = &orders[0];
println!("First: {}", first);
orders.push(45);
println!("{:?}", orders);
}
First: 102
[102, 70, 38, 45]
The borrow first doesn't live until the }, only until its last use, the first println! line. After that, push may borrow orders to change it. This feature is called non-lexical lifetimes (NLL), which means a borrow's life doesn't follow the curly braces of a block. NLL has been there since the 2018 edition (the 2018 version of Rust's language rules). So when you get E0502 or E0499, the fix is often just to put the uses of the old borrow above the new one.
A reference can't outlive its data
In this code, let note; makes a variable that gets its value later. note borrows slip inside a { } block, and is then used after that block closes:
fn main() {
let note;
{
let slip = String::from("2x sweet pancake");
note = &slip;
}
println!("{}", note);
}
error[E0597]: `slip` does not live long enough
--> src/main.rs:5:16
|
4 | let slip = String::from("2x sweet pancake");
| ---- binding `slip` declared here
5 | note = &slip;
| ^^^^^ borrowed value does not live long enough
6 | }
| - `slip` dropped here while still borrowed
7 | println!("{}", note);
| ---- borrow later used here
slip is dropped at the } that closes the inner block, but note is still used after it. If this were allowed, note would be a dangling reference. The span a borrow lives for is called its lifetime. The compiler makes sure every lifetime ends before its data is thrown away.
A function that returns a reference sometimes has to write out its lifetime. The function longest below picks the longer of two texts:
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
println!("{}", longest("sweet pancake", "iced tea"));
}
It prints sweet pancake. Without <'a>, fn longest(a: &str, b: &str) -> &str is refused with E0106 missing lifetime specifier, because the compiler can't tell whether the result borrows from a or from b. 'a is just a name for one lifetime, and <'a> after the function name introduces that name, like <T> in the generics lesson. With 'a in all three places, the function's first line says: "the result may be used as long as both a and b are alive". A lifetime doesn't make any value live longer. It only describes to the compiler how the result is tied to the parameters. A function that builds its own String and returns a &String is also refused with E0106. The compiler's advice is right: instead, you are more likely to want to return an owned value, that is, return the String.
Slices: borrowing a part
This program borrows part of a text, part of a Vec and a whole array. The function total adds up the numbers of any slice it is given:
fn total(item: &[u32]) -> u32 {
item.iter().sum()
}
fn main() {
let slip = String::from("2x sweet pancake");
let portions: &str = &slip[0..2];
let menu: &str = &slip[3..];
let orders = vec![102, 70, 38];
let board: [u32; 4] = [32, 38, 5, 5];
println!("{} | {}", portions, menu);
println!("{:?}", &orders[1..]);
println!("{}", total(&orders));
println!("{}", total(&orders[1..]));
println!("{}", total(&board));
}
2x | sweet pancake
[70, 38]
210
108
80
- A slice is a borrow of a run of items that sit next to each other.
&slip[0..2]borrows from byte 0 up to before byte 2, which is2x.&slip[3..]borrows from byte 3 to the end of the text. - The
&stryou've used from the start is a slice of text.&[u32]is a slice ofu32numbers, from a Vec or an array. Nothing is copied: a slice holds only a pointer and a length, 16 bytes in total. - The
&[u32]parameter oftotalaccepts&orders(a Vec),&orders[1..]and&board(an array). In the same way, a&strparameter accepts&slipand the text literal"iced tea". That's whyfn length_of(s: &str)is more common than the version with&String. - A slice is a borrow too, so it follows the same rule: while
portionswill still be used,slip.push_str(...)is refused with E0502.
⚠️ The borrow checker messages you will see most
- Changing something that is still borrowed. A
pushorpush_strwhile a&borrow is still used afterwards: E0502. Finish using the borrow first, then change the value. - Two
&mutat once. E0499cannot borrow ... as mutable more than once at a time. End the first borrow before making the second. mutin only one place. You needlet mut,&mutin the call and&mut Tin the parameter. If one is missing, the compiler refuses with E0596 or E0308.- Returning a borrow of local data.
fn make_slip() -> &Stringis refused (E0106), because data made inside the function is thrown away when that function ends. Return theString.
TL;DR: &slip makes a reference (a borrow) to read the variable slip, and &mut slip makes a borrow to change it. The owner stays slip, so there is no move, and nothing is dropped when the borrow ends. At any time there may be many & or exactly one &mut (E0502, E0499), and while the value is borrowed, even the owner may not change it (E0506). The rule prevents dangling references, which are borrows of memory already given back, such as a borrow into a Vec whose items move to a new place on push. A borrow ends at its last use (NLL), not at the }. A reference can't outlive its data (E0597). A function that returns a reference taken from two parameters writes out its lifetime (the span a borrow lives for), named 'a here: fn longest<'a>(a: &'a str, b: &'a str) -> &'a str. Slices (&str, &[u32]) borrow a run of items that sit next to each other. A slice is only 16 bytes in size, and slices make the most flexible parameter types.
⚡ & borrows to read
Write:
fn cook(slip: &String) {
println!("Cooked: {}", slip);
}
cook(&slip);
println!("Cashier: {}", slip);
Meaning: slip is a String. &slip makes a reference (a borrow): only the pointer is sent to cook, and the owner stays slip. A borrower is not an owner, so nothing is dropped when cook ends, and slip can still be printed.
⚡ &mut borrows to change
Write:
fn add_item(slip: &mut String, item: &str) {
slip.push_str(item);
}
add_item(&mut slip, ", 1x iced tea");
Meaning: &mut slip lends slip so that add_item can change it, here by adding text with push_str. Changing through a borrow needs mut in three places: let mut slip, &mut slip in the call, and the parameter type &mut String.
⚡ Many readers, or one writer
Guess first: cashier and kitchen both borrow slip with &mut slip, then both are used to add text. Does the code compile?
No. Only one &mut may exist at a time: E0499 cannot borrow ... as mutable more than once at a time.
Meaning: At any one time, a value may have any number of & borrows (to read), or exactly one &mut borrow (to change). A borrow ends at the last line where it is used, so finish using the old borrow before you make a new one.