Skip to content

cat posts/en/rust-lernen-03-ownership.md

Learning Rust (Part 3): Ownership

Every value has exactly one owner, and when the owner goes away, the value is freed. What that means for assignments and function calls, why a String isn't copied, and how logbuch builds an error report.

Claymation figure: a ginger cat sits in a cardboard box with a grumpy look and closed eyes, next to a second, empty box.

In part 1, there was a sentence you may have tried out: drop the & from &pfad, and the compiler speaks up. Today, that promise gets kept. fs::read_to_string(&pfad) becomes fs::read_to_string(pfad) (pfad is German for path):

error[E0382]: borrow of moved value: `pfad`
  --> src/main.rs:15:16
   |
 5 |     let pfad = env::args().nth(1).expect("Usage: logbuch <FILE>");
   |         ---- move occurs because `pfad` has type `String`, which does not implement the `Copy` trait
 6 |     let text = fs::read_to_string(pfad).expect("Couldn't read file");
   |                                   ---- value moved here
...
15 |     println!("{pfad}: {zeilen} lines, {fehler} errors ({anteil:.1} %)");
   |                ^^^^ value borrowed here after move
   |
help: consider borrowing `pfad`
   |
 6 |     let text = fs::read_to_string(&pfad).expect("Couldn't read file");
   |                                   +

Line 6 passes pfad to a function. From then on, the value belongs to the function, and main can't touch it in line 15 anymore. In Python, that would be absurd: a name you pass to a function is still there afterward. That difference is what this part is about. The concept behind it is called ownership.

The rules

Ownership fits into three sentences:

  1. Every value has an owner, usually a variable.
  2. There is always exactly one owner.
  3. When the owner goes out of scope, the value is freed.

Everything else in this part follows from these. A variable's scope is the block in curly braces where it's declared. At the end of main, the scope of pfad and text ends, and Rust frees the memory.

How Python does it

In Python, names are just references. Two names can point to the same object:

logs = ["access.log"]
alias = logs
alias.append("error.log")
print(logs)  # ['access.log', 'error.log']

CPython decides when to free the list with a counter: every object knows how many references to it exist. When the counter drops to zero, the object is gone. For cycles, whose counters never drop to zero, a garbage collector runs on top. That costs memory for the counters and time for the counting, but it takes all the bookkeeping off your hands.

Rust has no garbage collector and counts references only if you explicitly ask for it (that's what the Rc type is for). Instead, the compiler decides at compile time when each value gets freed. That only works because there is always exactly one owner: the end of its scope is the moment.

Moving

So what happens on an assignment?

fn main() {
    let a = String::from("access.log");
    let b = a;
    println!("{a} {b}");
}
error[E0382]: borrow of moved value: `a`
 --> src/main.rs:4:16
  |
2 |     let a = String::from("access.log");
  |         - move occurs because `a` has type `String`, which does not implement the `Copy` trait
3 |     let b = a;
  |             - value moved here
4 |     println!("{a} {b}");
  |                ^ value borrowed here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let b = a.clone();
  |              ++++++++

let b = a makes b the new owner. This is called a move: the value changes owners, and a is invalid afterward. With two owners, both would want to free the memory at the end. In C, that would be a double free, one of the classic security holes. Rust prevents it by locking the old name.

By the way, String::from("access.log") turns the literal into a String of its own. You'll see why that's necessary further down.

Copying: Copy and clone

With numbers, the same thing works without complaint (kopie is German for copy):

let status: u16 = 404;
let kopie = status;
println!("{status} {kopie}");

u16 is Copy. Types with this property are copied bit for bit on assignment, and both variables stay valid. Copy types include all number types, bool, char, and tuples or arrays made up only of Copy types. The error message above calls Copy a trait. Part 10planned explains what exactly that is.

A String isn't Copy because it owns memory. It consists of two parts. On the stack sit a pointer, the length, and the capacity. The actual characters live on the heap. A bitwise copy would only duplicate the pointer, and then two owners would point to the same characters. That's exactly what the rules are there to prevent. The companion article Stack and heapplanned measures what this means in memory and how Python handles it.

If you really want a copy, you say so: a.clone() allocates a new block on the heap and copies the characters into it. The compiler suggests this but adds “if the performance cost is acceptable.” For a file name, it doesn't matter. For a 2 GB log, one clone per function call would be a bad idea.

Functions take and give

A function call is a move, just like an assignment. Suppose zaehle_zeilen (German for count_lines) takes a String instead of &str:

fn zaehle_zeilen(text: String) -> usize {
    text.lines().count()
}

fn main() {
    let text = String::from("one\ntwo\n");
    let zeilen = zaehle_zeilen(text);
    println!("{zeilen} lines, {} bytes", text.len());
}
error[E0382]: borrow of moved value: `text`
 --> src/main.rs:8:42
  |
6 |     let text = String::from("one\ntwo\n");
  |         ---- move occurs because `text` has type `String`, which does not implement the `Copy` trait
7 |     let zeilen = zaehle_zeilen(text);
  |                                ---- value moved here
8 |     println!("{zeilen} lines, {} bytes", text.len());
  |                                          ^^^^ value borrowed here after move
  |
note: consider changing this parameter type in function `zaehle_zeilen` to borrow instead if owning the value isn't necessary
 --> src/main.rs:1:24
  |
1 | fn zaehle_zeilen(text: String) -> usize {
  |    -------------       ^^^^^^ this parameter takes ownership of the value
  |    |
  |    in this function
...

The parameter text is now the owner. At the end of zaehle_zeilen, its scope ends, and the text gets freed before main can count the bytes. The note: already points to the right fix: the function doesn't need to own the text at all. It only wants to read it.

Ownership can also leave a function, through the return value. A function can create a value and hand it over to the caller (kopfzeile is German for header line, zeile for line):

fn kopfzeile(pfad: &str) -> String {
    let zeile = format!("Analysis of {pfad}");
    zeile
}

zeile belongs to the function. If the function didn't return zeile, the String would be freed at the end. Instead, it moves out to the caller, which is now its owner. Writing format! directly as the last expression would be shorter. For the explanation, the variable is easier to follow.

A nice detail shows how seriously Rust means this. The drop function frees a value immediately, and this is how the standard library defines it:

pub fn drop<T>(_x: T) {}

It does nothing. It takes ownership of the value, and because the scope of _x ends right away, the value is freed. If you use text after drop(text), you get E0382 again. The compiler then earnestly suggests drop(text.clone()), which compiles but misses the point.

When does a value get freed?

With drop, you free a value early. Otherwise, that happens at the end of the scope, and normally at a point that's already fixed at compile time:

fn main() {
    let pfad = String::from("access.log");
    {
        let text = String::from("…");
        println!("{pfad}: {} bytes", text.len());
    } // text is freed here
    println!("{pfad}");
} // pfad is freed here

In CPython, simple cases are similarly deterministic, because the counter drops to zero as soon as the last reference disappears. With cycles, though, the garbage collector decides, and it runs whenever it wants. In Rust, that case only exists if you opt into counting with Rc yourself. Freeing at the end of the scope applies to other resources, too: an open file gets closed at the end of the scope, a lock gets released. Python's with does the same, except that there you have to remember to write it.

String and &str

Two text types have been tagging along since part 1. Now the difference between them makes sense:

  • String owns its characters. They live on the heap, the String can grow, and it frees them when its owner goes away.
  • &str is a borrowed view of characters it doesn't own. A &str frees nothing.

A literal like "access.log" is a &str. Its characters are baked into the program and belong to no one who would have to free them. That's why the only way to get a text of your own that you can change is String::from("access.log") or "access.log".to_string().

Python's str is immutable. A Rust String, on the other hand, can be extended, for example with push_str, if the variable is mut. logbuch (German for logbook) needs that in a moment.

The functions in logbuch all take &str because they only read. And because a &String turns into a &str automatically, you can pass them &text just as well as a literal. How borrowing works in detail is the topic of the next partplanned.

logbuch: the error report

Now logbuch should not only count but also show which requests failed. The new function builds a text for that and hands it over (fehlerbericht is German for error report, bericht for report):

fn fehlerbericht(text: &str) -> String {
    let mut bericht = String::new();
    for zeile in text.lines() {
        let status = statuscode(zeile);
        if status >= 400 {
            let pfad = zeile.split_whitespace().nth(6).expect("Line without path");
            bericht.push_str(&format!("  {status} {pfad}\n"));
        }
    }
    bericht
}

fehlerbericht borrows the text (&str) and owns the report (String). String::new() creates an empty String that can grow. push_str appends to it, like += on a Python string, only without creating a new object every time. format! returns a new String, and push_str wants a &str, hence the &. At the end, bericht leaves the function as the return value, and main becomes its owner. The path sits at index 6, between the method and the protocol.

main gets two more lines:

    let bericht = fehlerbericht(&text);
    print!("{bericht}");

print! is println! without the newline at the end; every report line already has one. Two tests also go into the tests module (their names mean “report names failed paths” and “report without errors is empty”):

    #[test]
    fn bericht_nennt_fehlerhafte_pfade() {
        let text = format!("{ZEILE_200}\n{ZEILE_404}\n");
        assert_eq!(fehlerbericht(&text), "  404 /wp-login.php\n");
    }

    #[test]
    fn bericht_ohne_fehler_ist_leer() {
        assert_eq!(fehlerbericht(ZEILE_200), "");
    }

Here, assert_eq! compares a String with a literal, that is, with a &str. That works because Rust ships a comparison for this combination.

$ cargo test
...
test result: ok. 8 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 rest of main.rs is unchanged from part 2.

Exercises

1. What compiles? For each of the three println! lines, decide whether it compiles before you try it.

fn main() {
    let status: u16 = 404;
    let kopie = status;
    println!("{status} {kopie}");

    let pfad = String::from("/favicon.ico");
    let kopie = pfad;
    println!("{pfad} {kopie}");

    let literal = "/favicon.ico";
    let kopie = literal;
    println!("{literal} {kopie}");
}
Solution Only the middle one fails, with E0382 for `pfad`. `u16` is `Copy`. The surprise is the third one: `&str` is `Copy`, too. Only the reference gets copied, not the characters, and a reference can exist any number of times because it frees nothing. The line `let kopie = …` works three times in a row thanks to shadowing.

2. What does this print?

fn main() {
    let a = String::from("outer");
    {
        let b = String::from("inner");
        let a = b;
        println!("{a}");
    }
    println!("{a}");
}
Solution
inner
outer
The inner `let a = b` moves `b` into a new `a` that only shadows the outer one. At the end of the inner block, “inner” is freed, and the outer `a` is visible again. Nothing ever touched it.

3. There and back. Rewrite fehlerbericht so that the appending happens in a separate function ergaenze (German for append) that takes the report as a String and returns it again. What do you notice about the call?

Solution
fn ergaenze(mut bericht: String, status: u16, pfad: &str) -> String {
    bericht.push_str(&format!("  {status} {pfad}\n"));
    bericht
}
`mut` in front of the parameter makes the variable mutable inside the function. The call in the loop reads `bericht = ergaenze(bericht, status, pfad);`. The report moves in and back out, and that works. But it's clumsy: the function only wants to change the report, not own it. There's a better way to do that.

Next up

The better way is called borrowing. With & and &mut, a function gets access to a value without owning it. Borrowing comes with its own rules, and the compiler checks them strictly. Part 4planned shows them and explains why logbuch gets by without a single copy.

0 comments

No comments yet. Be the first!