Rust Playbook

Course › Week 1 · Basics and ownership › Day 4 · lesson 4 of 42 · 15 min reading + 60–90 min practice

Borrowing and slices

Lend a value without giving it away: many readers or one writer, never both, and &str slices.

references&mutborrow checker&strslices

On this page
  1. 1. & lends a value
  2. 2. A plain reference is read-only
  3. 3. &mut lends it for changing
  4. 4. The rule: many readers, or one writer
  5. 5. A reference can never outlive its value
  6. 6. &str: a view into text
  7. 7. Slices of arrays
  8. Coming from PHP
  9. Practice
  10. Remember

Yesterday, every function call took ownership of the String you passed. Today you lend it instead. A reference lets a function use a value while the caller keeps owning it. Making a reference is called borrowing.

There are only two kinds of reference, and one rule about mixing them. Learn the rule today and most of the “fighting the borrow checker” stories you have heard will make sense.

1. & lends a value

&guest makes a reference to guest. The parameter type &String says “I borrow a String, I do not own it”. When the function ends, nothing is freed, because it never owned anything.

src/main.rs
fn welcome(name: &String) {
    println!("Welcome, {name}!");
}

fn main() {
    let guest = String::from("Omar");

    welcome(&guest);
    welcome(&guest);
    println!("Checked in: {guest}");
}
$ cargo run
Welcome, Omar!
Welcome, Omar!
Checked in: Omar

This is the fix you would ship for yesterday’s exercise. In section 6 it gets one small improvement.

2. A plain reference is read-only

Like variables, references are immutable by default. A function that borrows with & cannot change the value:

src/main.rsdoes not compile
fn add_title(name: &String) {
    name.insert_str(0, "Mr ");
}

fn main() {
    let guest = String::from("Omar");
    add_title(&guest);
    println!("{guest}");
}
cargo build
error[E0596]: cannot borrow `*name` as mutable, as it is behind a `&` reference
 --> src/main.rs:2:5
  |
2 |     name.insert_str(0, "Mr ");
  |     ^^^^ `name` is a `&` reference, so it cannot be borrowed as mutable
  |
help: consider changing this to be a mutable reference
  |
1 | fn add_title(name: &mut String) {
  |                     +++

For more information about this error, try `rustc --explain E0596`.
error: could not compile `hello` (bin "hello") due to 1 previous error

3. &mut lends it for changing

To let a function change a borrowed value, three things must say so: the variable is mut, the call passes &mut, and the parameter type is &mut String. Mutation is never hidden.

src/main.rs
fn add_title(name: &mut String) {
    name.insert_str(0, "Mr ");
}

fn main() {
    let mut guest = String::from("Omar");
    add_title(&mut guest);
    println!("{guest}");
}
$ cargo run
Mr Omar

4. The rule: many readers, or one writer

RuleAt any moment, a value can have either any number of & references, or exactly one &mut reference. Never both.

Why: if one part of the code could change a value while another part is reading it, the reader could see half a change, or point at memory that the change just moved. The rule makes that impossible to write.

Two writers at once

src/main.rsdoes not compile
fn main() {
    let mut note = String::from("Late check-in");

    let first = &mut note;
    let second = &mut note;

    first.push_str(" after 22:00");
    second.push_str(", key in the lockbox");
}
cargo build
error[E0499]: cannot borrow `note` as mutable more than once at a time
 --> src/main.rs:5:18
  |
4 |     let first = &mut note;
  |                 --------- first mutable borrow occurs here
5 |     let second = &mut note;
  |                  ^^^^^^^^^ second mutable borrow occurs here
6 |
7 |     first.push_str(" after 22:00");
  |     ----- first borrow later used here

For more information about this error, try `rustc --explain E0499`.
error: could not compile `hello` (bin "hello") due to 1 previous error

A writer while someone is reading

summary reads note, and is still used on the last line. In between, the code tries to change note:

src/main.rsdoes not compile
fn main() {
    let mut note = String::from("Late check-in");

    let summary = &note;
    note.push_str(" after 22:00");

    println!("{summary}");
}
cargo build
error[E0502]: cannot borrow `note` as mutable because it is also borrowed as immutable
 --> src/main.rs:5:5
  |
4 |     let summary = &note;
  |                   ----- immutable borrow occurs here
5 |     note.push_str(" after 22:00");
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
6 |
7 |     println!("{summary}");
  |                ------- immutable borrow later used here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `hello` (bin "hello") due to 1 previous error

A borrow ends at its last use

Move the println! up, and it compiles. A reference only counts as alive until the last line that uses it, not until the end of the braces:

src/main.rs
fn main() {
    let mut note = String::from("Late check-in");

    let summary = &note;
    println!("{summary}"); // last use of summary: the borrow ends here

    note.push_str(" after 22:00"); // so changing note is fine now
    println!("{note}");
}
$ cargo run
Late check-in
Late check-in after 22:00

When you get E0499 or E0502, the fix is usually to reorder: finish reading before you start writing.

5. A reference can never outlive its value

A function cannot return a reference to something it created, because that something is freed when the function ends. In C this compiles and crashes later. Rust refuses:

src/main.rsdoes not compile
fn default_note() -> &String {
    let note = String::from("No special requests");
    &note
}

fn main() {
    println!("{}", default_note());
}
cargo build
error[E0106]: missing lifetime specifier
 --> src/main.rs:1:22
  |
1 | fn default_note() -> &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 default_note() -> &'static String {
  |                       +++++++
help: instead, you are more likely to want to return an owned value
  |
1 - fn default_note() -> &String {
1 + fn default_note() -> String {
  |

For more information about this error, try `rustc --explain E0106`.
error: could not compile `hello` (bin "hello") due to 1 previous error

The message talks about “lifetimes”, which you will learn to read in Week 2. The fix needs none of that: return the String itself and move ownership to the caller, as yesterday.

src/main.rs
fn default_note() -> String {
    String::from("No special requests")
}

fn main() {
    println!("{}", default_note());
}
$ cargo run
No special requests

6. &str: a view into text

A slice is a reference to part of a value

&line[1..20] borrows bytes 1 to 19 of the String, without copying them. Its type is &str, a string slice: a pointer and a length.

src/main.rs
fn main() {
    let line = String::from("[2026-11-30 14:02:11] production.ERROR: Payment failed");

    let timestamp: &str = &line[1..20];
    println!("{timestamp}");
}
$ cargo run
2026-11-30 14:02:11

Text in quotes is already a &str

A string literal like "Payment failed" is a &str that points into the program itself. That is why functions that only read text should take &str, not &String: they then accept both a literal and a borrowed String.

src/main.rs
fn is_error(line: &str) -> bool {
    line.contains(".ERROR:")
}

fn main() {
    let from_file = String::from("[2026-11-30 14:02:11] production.ERROR: Payment failed");

    println!("{}", is_error(&from_file)); // a borrowed String
    println!("{}", is_error("[2026-11-30 14:05:40] production.INFO: Ok")); // a literal
}
$ cargo run
true
false

&from_file is a &String, and Rust turns it into a &str automatically when the parameter asks for one. So the rule for this course: parameters that read text are &str. Section 1’s welcome should take name: &str.

Slices count bytes, not letters

The numbers in [1..20] are byte positions. Text is stored as UTF-8, where é, ø or any Arabic letter takes two or more bytes. Cut in the middle of one and the program stops:

src/main.rs
fn main() {
    let city = String::from("Ærøskøbing");

    let first_letter = &city[0..1];
    println!("{first_letter}");
}
$ cargo run
thread 'main' (1035) panicked at src/main.rs:4:29:
end byte index 1 is not a char boundary; it is inside 'Æ' (bytes 0..2 of string)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
exit code 101

This compiles, then panics: the program stops with a message and exit code 101. Æ takes two bytes, so 0..1 cuts it in half. Slicing by fixed positions is fine for known ASCII formats like the log timestamp above; for human text, use methods that work in characters, like .chars(), which you will meet with iterators in Week 3.

7. Slices of arrays

The same idea works for arrays: &[u64] is a view of some u64s, of any length. A function that takes &[u64] accepts a whole array or any part of one.

src/main.rs
fn total(prices: &[u64]) -> u64 {
    let mut sum = 0;
    for price in prices {
        sum += price;
    }
    sum
}

fn main() {
    let week: [u64; 7] = [15_010, 15_010, 15_010, 15_010, 18_000, 18_000, 15_010];

    println!("whole week: {}", total(&week));
    println!("weekend:    {}", total(&week[4..6]));
}
$ cargo run
whole week: 111050
weekend:    36000

Coming from PHP

PHP has references too, with &. They look alike and are very different:

references.php
<?php

function addTitle(string &$name): void
{
    $name = 'Mr ' . $name;
}

$guest = 'Omar';
$alias = &$guest;     // a second name for the same variable
addTitle($guest);     // changes it through the reference
$alias .= '!';        // and so can $alias, at the same time

echo $guest;          // Mr Omar!

In PHP, any number of references can change the same variable at once. Rust allows one &mut at a time, and no readers while it exists. And in PHP, passing a plain object to a function always lets the function change it; in Rust, the signature tells you: & reads, &mut changes, a plain type takes ownership.

PracticeThe Book ch. 4.2–4.3, Rustlings move_semantics 4–5 and vecs

Read chapter 4.2 and 4.3 in the Brown edition.

In Rustlings: 06_move_semantics 4 and 5, then 05_vecs 1 and 2.

Exercise: the log level

A Laravel log line looks like [2026-11-30 14:02:11] production.ERROR: Payment failed. Write fn level_of(line: &str) -> &str that returns the part between the first . after the timestamp and the following :, here "ERROR". Every line in this exercise is well formed; Day 5 handles bad ones.

Two methods help: line.find(".") gives Some(position) of the first match, and .unwrap() takes the number out (Day 5 explains Some and why unwrap is not for real code). Start from byte 22, right after the timestamp and its space.

Show the solution
src/main.rs
fn level_of(line: &str) -> &str {
    let rest = &line[22..]; // after "[2026-11-30 14:02:11] "
    let dot = rest.find('.').unwrap(); // the dot after "production"
    let colon = rest.find(':').unwrap(); // the colon after the level
    &rest[dot + 1..colon]
}

fn main() {
    println!(
        "{}",
        level_of("[2026-11-30 14:02:11] production.ERROR: Payment failed")
    );
    println!(
        "{}",
        level_of("[2026-11-30 14:05:40] local.INFO: Queue started")
    );
}
$ cargo run
ERROR
INFO

The returned &str borrows from line: no text was copied. Notice that the compiler did not ask you for anything special to return a slice of a parameter. Week 2 explains why.

Remember

  • & reads, &mut changes, a plain type takes ownership: the signature tells you which.
  • Many readers or one writer, never both; a borrow ends at its last use, so reorder before anything else.
  • Parameters that read text are &str.

Tomorrow: your own types. A struct for a log line, an enum for its level, and match.