archive / 2019

Trying Rust: a week of arguing with the borrow checker

I wrote my first real Rust program: a small CLI tool that counts HTTP status codes in access logs. About ownership, error messages that beat some code reviews, and whether I'm a convert now.

For a few years now I’ve been hearing people rave about Rust, and for a few years I’ve nodded politely and gone back to writing Go. But since December there’s the Rust 2018 edition, the book has been rewritten, and I needed an excuse to learn something that wasn’t “yet another YAML format for Kubernetes”. So: a week of Rust in the evenings.

The goal was deliberately small. A tool that takes access logs on stdin and counts how many of each HTTP status code are in there. Something I currently do with an awk one-liner, but as a real program. No async, no web framework, no dependencies. Just getting to know the language.

Installing and first impressions#

Installation goes through rustup, which is immediately one of the best things about the ecosystem:

curl https://sh.rustup.rs -sSf | sh
cargo new statuscount
cd statuscount
cargo run

Yes, curl | sh. I know. Jef from the agency wouldn’t look me in the eye for a week.

cargo does everything: creating the project, dependencies, building, testing, formatting with cargo fmt. Anyone who lived through the early days of Go and GOPATH gets a little jealous here.

Ownership, or: why won’t this compile?#

The first evening went entirely into understanding ownership. On paper the principle is simple:

  • Every value has exactly one owner.
  • When the owner goes out of scope, the value is dropped.
  • You can borrow a value (a reference), either many times read-only, or once mutably. Never both at the same time.

On paper, I said. In practice I wrote this, which is fine in pretty much any other language:

fn main() {
    let mut names = vec![String::from("jef")];
    let first = &names[0];
    names.push(String::from("sarah"));
    println!("{}", first);
}

And the compiler said no:

error[E0502]: cannot borrow `names` as mutable because it is also borrowed as immutable

My first reaction was irritation. My second reaction, after some reading, was: oh. A Vec that grows can move its memory. Then first points at memory that no longer exists. In C that’s a use-after-free you find three weeks later in production. Rust won’t even let you compile it.

That’s the heart of the language, I think. The borrow checker isn’t a bully, it’s a colleague who is very strict but usually right. And the error messages are genuinely exceptional: they point at where the borrow starts, where it clashes, and often even suggest a fix.

The tool itself#

After some fumbling I ended up with this. It expects the “combined” log format of nginx and Apache, where the status code comes right after the quoted request:

use std::collections::HashMap;
use std::env;
use std::io::{self, BufRead};

fn status_from_line(line: &str) -> Option<u16> {
    // ... "GET /index.html HTTP/1.1" 200 2326 "-" "curl/7.58.0"
    let after_request = line.splitn(3, '"').nth(2)?;
    after_request.split_whitespace().next()?.parse().ok()
}

fn main() -> io::Result<()> {
    let errors_only = env::args().any(|a| a == "--errors");

    let stdin = io::stdin();
    let mut counts: HashMap<u16, u64> = HashMap::new();
    let mut unparsed = 0u64;

    for line in stdin.lock().lines() {
        let line = line?;
        match status_from_line(&line) {
            Some(code) if errors_only && code < 400 => {}
            Some(code) => *counts.entry(code).or_insert(0) += 1,
            None => unparsed += 1,
        }
    }

    let mut result: Vec<(u16, u64)> = counts.into_iter().collect();
    result.sort_by(|a, b| b.1.cmp(&a.1));

    for (code, count) in &result {
        println!("{}\t{}", code, count);
    }
    if unparsed > 0 {
        eprintln!("{} lines not recognised", unparsed);
    }
    Ok(())
}

A few things I really like here:

  • Option and the ? operator. status_from_line returns either Some(code) or None. Every step that can fail ends with ?: if it fails, the function returns None right there. No null, no exceptions, and still short. Compare that to the if err != nil staircase I climb every day in Go.
  • &str versus String. The function borrows the line (&line), it doesn’t take ownership. So the loop could keep using the line afterwards if it needed to. The difference between those two string types confused me at first, but it’s actually very logical: a String is yours, a &str is borrowed.
  • match with guards. That Some(code) if errors_only && code < 400 => {} line reads almost like a sentence. And the compiler checks that I’ve handled every case.
  • entry().or_insert(0). The HashMap API is well thought out. One line for “add one, or start at zero”.

Usage:

cargo build --release
zcat /var/log/nginx/access.log.*.gz | ./target/release/statuscount --errors

Is it faster than awk?#

Of course I measured it. On a log file of roughly 2 GB the Rust version was about four times faster than my awk one-liner. But let’s be honest: the difference between 9 and 35 seconds hasn’t changed my life. Speed wasn’t the point.

What I think of it#

After a week:

The good: the compiler catches a whole class of bugs that in other languages I only see in production. Cargo is excellent. The documentation and the book are of a level I rarely see. And the error messages, I already said it, but I’ll say it again: they’re better than some code reviews I’ve received.

The less good: the learning curve is really steep. I only half understand lifetimes so far, and as soon as you start putting references inside structs, you’re busy for a while. Compiling takes noticeably longer than with Go. And for the services we build at the scale-up (lots of network, lots of JSON, lots of “just an API”), I don’t immediately see why Rust would be better than Go. The async story is also still very much in motion.

Am I going to rewrite our services? No. Will I reach for Rust again the next time I need a CLI tool? Yes, probably. It feels a bit like the first time I used a statically typed language after years of PHP: annoying at first, and then you wonder how you ever managed without.

Segfault walked across the keyboard twice while I was writing this post, by the way. Whatever she typed didn’t compile. So the borrow checker protects against cats too.

    Tip: / opens search, ↑↓ to select, ↵ to open.