Skip to content

cat posts/en/rust-lernen-04-borrowing.md

Learning Rust (Part 4): Borrowing

References with & and &mut, the “many readers or one writer” rule, and slices. logbuch reads paths from the line without copying a single character.

A pizza server lifts a single slice out of a pepperoni pizza on a wooden board. Long strings of cheese stretch back to the rest of the pizza.

A classic among Python bugs: changing a list while a loop is running over it (zeilen is German for lines).

zeilen = ["404 /a", "404 /b", "200 /"]
for z in zeilen:
    if z.startswith("4"):
        zeilen.remove(z)
print(zeilen)  # ['404 /b', '200 /']

404 /b survived. After the first remove, everything moves up one position, and the loop skips over the second element. Python doesn't say a word. Here's the same attempt in Rust, with a String instead of a list (zeile is German for line):

fn main() {
    let mut text = String::from("200 /\n404 /favicon.ico\n");
    for zeile in text.lines() {
        if zeile.starts_with('4') {
            text.push_str("Error found\n");
        }
    }
    println!("{text}");
}
error[E0502]: cannot borrow `text` as mutable because it is also borrowed as immutable
 --> src/main.rs:5:13
  |
3 |       for zeile in text.lines() {
  |       -            ------------
  |       |            |
  |       |            immutable borrow occurs here
  |  _____|            immutable borrow later used here
  | |
4 | |         if zeile.starts_with('4') {
5 | |             text.push_str("Error found\n");
  | |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
6 | |         }
7 | |     }
  | |_____- this for loop borrows `text` immutably, preventing mutation within its body
  |
  = help: consider using an index-based loop instead, or collecting modifications into a separate collection

Rust doesn't let it get that far. And here, more would be at stake than a skipped element: zeile points into the memory of text. If the space runs out during push_str, the String can move to a larger block on the heap, and then zeile points to freed memory. The companion article on stack and heap showed when a String needs more space.

Borrowing

In part 3, every value has exactly one owner. So that not every function has to take it over, there are references: &text borrows the value, and the owner stays the same. This is called borrowing, and you've been using it since part 1, with every &text.

There are two kinds:

  • &T is a shared reference. Through it, you can read but not change anything.
  • &mut T is a mutable reference. Through it, you can change the value.

One rule applies to both: At any given time, there are either any number of & or exactly one &mut. Many readers or one writer, never both. That's exactly the rule the loop above broke: lines() reads, push_str writes.

Two &mut at the same time fail the same way (bericht is German for report):

fn main() {
    let mut bericht = String::new();
    let a = &mut bericht;
    let b = &mut bericht;
    a.push_str("404 /favicon.ico\n");
    b.push_str("404 /wp-login.php\n");
}
error[E0499]: cannot borrow `bericht` as mutable more than once at a time
 --> src/main.rs:4:13
  |
3 |     let a = &mut bericht;
  |             ------------ first mutable borrow occurs here
4 |     let b = &mut bericht;
  |             ^^^^^^^^^^^^ second mutable borrow occurs here
5 |     a.push_str("404 /favicon.ico\n");
  |     - first borrow later used here

The part of the compiler that checks this rule is called the borrow checker. Most of the error messages in your first weeks with Rust come from it. It's also part of the reason why Rust has no data races without unsafe: if two threads access the same value at the same time and at least one of them writes, that would take a &mut next to a second reference. Part 11planned takes care of the rest.

How long a borrow lasts

The message above says “first borrow later used here.” That's what counts: a borrow doesn't last until the end of the block, but until the last place where the reference is used. This compiles (erste is German for first):

fn main() {
    let mut text = String::from("200 /\n");
    let erste = text.lines().next().expect("empty");
    println!("{erste}");
    text.push_str("404 /favicon.ico\n");
    println!("{text}");
}

After the first println!, nobody needs erste anymore, so text is free again for push_str. If you swap println!("{erste}") and push_str, you get E0502. When the borrow checker complains, moving a line up or down often does the trick.

By the way, .next() gets the first element, and expect opens the container you know from nth.

A reference can't outlive its value

A second condition: a reference must not live longer than the value it points to. A function that returns a reference to its own local variable therefore fails right at the signature (kopfzeile is German for header line):

fn kopfzeile() -> &str {
    let zeile = String::from("Analysis");
    &zeile
}
error[E0106]: missing lifetime specifier
 --> src/main.rs:1:19
  |
1 | fn kopfzeile() -> &str {
  |                   ^ 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: instead, you are more likely to want to return an owned value
  |
1 - fn kopfzeile() -> &str {
1 + fn kopfzeile() -> String {
  |

zeile is freed at the end of the function, and a reference to it would point into nothing. In C, that would be a dangling pointer. It compiles there, with a warning at most, and the bug shows up only at runtime, or never. If you follow the first suggestion, which is cut from the output above, and write &'static str, the borrow checker reports E0515: “cannot return reference to local variable.” The compiler suggests returning the String itself instead, that is, handing over ownership, as in part 3. Part 9planned explains what a lifetime is and when you have to write it out.

&mut instead of there and back

Exercise 3 in part 3 moved the report into a function and back out again. With &mut, ergaenze (German for append) no longer needs ownership:

fn ergaenze(bericht: &mut String, status: u16, pfad: &str) {
    bericht.push_str(&format!("  {status} {pfad}\n"));
}

The function returns nothing. It changes the String it borrowed, and the caller keeps it. At the call site, the &mut is spelled out. If you leave out the mut, the compiler complains:

error[E0308]: mismatched types
 --> src/main.rs:7:14
  |
7 |     ergaenze(&bericht, 404, "/favicon.ico");
  |     -------- ^^^^^^^^ types differ in mutability
  |     |
  |     arguments to this function are incorrect
  |
  = note: expected mutable reference `&mut String`
                     found reference `&String`
...

In Python, any function can modify a list you pass to it, and you can't tell from the call. In Rust, it's right there: ergaenze(&mut bericht, …) changes bericht, zaehle_fehler(&text) doesn't.

Slices

That leaves the second half of the topic. You've known &str since part 1 as borrowed text. More precisely, a &str is a slice: a pointer to the first byte and a length in bytes. It can cover a whole String or just part of it:

let zeile = String::from("404 /favicon.ico");
let status = &zeile[..3]; // "404"
let pfad = &zeile[4..]; // "/favicon.ico"

..3 means “from the start up to, but not including, byte 3,” and 4.. means “from byte 4 to the end,” like zeile[:3] and zeile[4:] in Python. Nothing gets copied. status and pfad point into the memory of zeile, and as long as they're in use, zeile is borrowed.

The difference from Python lies in the word “byte.” Rust strings are UTF-8, and the boundaries of a slice have to fall on character boundaries. If they don't, you get a panic. More on that in exercise 2.

The same works for arrays: for an array zahlen: [u32; 4], &zahlen[1..3] is a &[u32], a slice of the array. This type comes back with Vec in part 8planned.

logbuch: paths without copying

So far, fehlerbericht pulled the path out of the line right inside the loop. Now this gets a function of its own, plus a second one that cuts off query strings. /suche?q=rust becomes /suche (anfrage_pfad is German for request path, ohne_query for without query, ende for end):

fn anfrage_pfad(zeile: &str) -> &str {
    zeile.split_whitespace().nth(6).expect("Line without path")
}

fn ohne_query(pfad: &str) -> &str {
    let ende = pfad.find('?').unwrap_or(pfad.len());
    &pfad[..ende]
}

Both take a &str and return a &str that points into the same text. split_whitespace and nth return slices of the line, and ohne_query cuts another piece off of that. Without any further annotations, the compiler knows that the result comes from the parameter, because there's only one. Why that's enough is also a topic for part 9planned.

find returns the byte position of the first ?. Since there may or may not be one, the position sits in a container again. unwrap_or(pfad.len()) takes the position or, if there's no ?, the full length. find always returns the start of a character, so the cut falls on a character boundary.

That makes fehlerbericht shorter:

fn fehlerbericht(text: &str) -> String {
    let mut bericht = String::new();
    for zeile in text.lines() {
        let status = statuscode(zeile);
        if status >= 400 {
            ergaenze(&mut bericht, status, ohne_query(anfrage_pfad(zeile)));
        }
    }
    bericht
}

Count what gets copied here. text is read once and belongs to main. lines(), anfrage_pfad, and ohne_query only return slices of it. The only characters that get copied are the ones that end up in the report: format! builds a new String from them, and push_str appends it to bericht. In Python, by contrast, zeile.split() alone creates a new list and copies almost every field into a str object of its own.

Two tests come with it (their names mean “reads request path” and “cuts off query”):

    #[test]
    fn liest_anfrage_pfad() {
        assert_eq!(anfrage_pfad(ZEILE_404), "/wp-login.php");
    }

    #[test]
    fn schneidet_query_ab() {
        assert_eq!(ohne_query("/suche?q=rust"), "/suche");
        assert_eq!(ohne_query("/feed.xml"), "/feed.xml");
    }
$ cargo test
...
test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
$ cargo run -- access.log
...
access.log: 5 lines, 2 errors (40.0 %)
  404 /favicon.ico
  404 /wp-login.php

The output is the same as in part 3.

Exercises

1. Two writers. Get the example with a and b to compile without deleting either of the two variables.

Solution Each borrow has to be over before the next one begins:
let mut bericht = String::new();
let a = &mut bericht;
a.push_str("404 /favicon.ico\n");
let b = &mut bericht;
b.push_str("404 /wp-login.php\n");
After the last use of `a`, there's no active borrow left, and `b` can begin.

2. Byte or character? What do the two lines print (gruss is German for greeting, "Grüße" for greetings)?

let gruss = String::from("Grüße");
println!("{}", &gruss[..2]);
println!("{}", &gruss[..3]);
Solution The first line prints `Gr`. The second one panics:
thread 'main' (53524) panicked at src/main.rs:4:26:
end byte index 3 is not a char boundary; it is inside 'ü' (bytes 2..4 of string)
`ü` takes up two bytes (see part 1), here bytes 2 and 3. A cut at byte 3 lands in the middle of the character. The compiler can't check this in advance, because the contents of a `String` are only known at runtime. That's why `logbuch` (German for logbook) only cuts at positions that `find` returned, or after characters it knows to be one byte long.

3. The method. Write fn methode(zeile: &str) -> &str (methode is German for method) that returns the HTTP method, so "POST" for ZEILE_404. Field 5 reads "POST, with the quotation mark. Copying isn't allowed.

Solution
fn methode(zeile: &str) -> &str {
    let feld = zeile
        .split_whitespace()
        .nth(5)
        .expect("Line without method");
    &feld[1..]
}
`&feld[1..]` (`feld` is German for field) drops the first byte, the quotation mark. Since it's a single byte, the cut is guaranteed to fall on a character boundary. A test for it: `assert_eq!(methode(ZEILE_404), "POST");`.

Next up

Status, path, and, if you did exercise 3, the method: logbuch pulls every field out of the line with a function of its own and splits the line from scratch every time. In part 5planned, everything goes into a type of its own, a struct LogEntry, with methods instead of loose functions.

0 comments

No comments yet. Be the first!