valfz

Rust from the command line

Structs, enums and pattern matching

Model a parsed log line with a struct and an enum, parse it by hand with match, if let and let else, then move the code into a module.

lesson
03 of 08
read
14 min

So far a request is a line of text. This lesson gives it a type: a struct for the fields tally needs and an enum for the class of its status code. Writing the parser by hand introduces Option, Rust’s replacement for null, and the pattern-matching forms that take it apart. The lesson ends by moving the new code into a module of its own.

A struct for one request

The first line of the sample file:

203.0.113.7 - - [28/Nov/2026:09:12:01 +0000] "GET / HTTP/1.1" 200 5123 "-" "Mozilla/5.0"

Of its fields, the summary needs four: the client address, the path inside the quoted request, the status code and the response size.

src/main.rs
#[derive(Debug)]
struct Entry {
    addr: String,
    path: String,
    status: u16,
    bytes: Option<u64>,
}

A struct is a record with named, typed fields. u16 and u64 are unsigned integers of 16 and 64 bits. #[derive(Debug)] asks the compiler to generate the code that prints the struct with {:?}, the format meant for programmers.

bytes is an Option<u64> because the size is not always a number. Apache writes - when a response has no body, as in lines 11 and 12 of the sample. Rust has no null. A value that may be absent has the type Option<T>, an enum from the standard library with the variants Some(value) and None, and the u64 inside cannot be reached without saying what happens for None.

The two strings are owned copies, following the rule from the last lesson. Lesson 5 revisits that choice.

An enum for the status class

src/main.rs
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StatusClass {
    Informational,
    Success,
    Redirection,
    ClientError,
    ServerError,
    Other,
}

impl StatusClass {
    fn from_code(code: u16) -> StatusClass {
        match code {
            100..=199 => StatusClass::Informational,
            200..=299 => StatusClass::Success,
            300..=399 => StatusClass::Redirection,
            400..=499 => StatusClass::ClientError,
            500..=599 => StatusClass::ServerError,
        }
    }
}

An enum is a type whose values are one of a fixed set of variants. The impl block attaches functions to it. from_code takes no self parameter, so it is called on the type: StatusClass::from_code(404). The derives make the enum behave like a small value: Clone and Copy let it be copied like an integer, PartialEq and Eq allow ==.

match compares a value against patterns from top to bottom and evaluates the arm of the first one that fits. 100..=199 is an inclusive range pattern. As written, this match does not compile:

error[E0004]: non-exhaustive patterns: `0_u16..=99_u16` and `600_u16..=u16::MAX` not covered
  --> src/main.rs:24:15
   |
24 |         match code {
   |               ^^^^ patterns `0_u16..=99_u16` and `600_u16..=u16::MAX` not covered
   |
   = note: the matched value is of type `u16`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern, a match arm with multiple or-patterns as shown, or multiple match arms
   |
29 ~             500..=599 => StatusClass::ServerError,
30 ~             0_u16..=99_u16 | 600_u16..=u16::MAX => todo!(),
   |

For more information about this error, try `rustc --explain E0004`.

A match must cover every possible value, and the compiler has worked out exactly which u16 values are missing. The same check applies to enums. Add a variant later, and every match over that enum without a catch-all arm stops compiling until the new case is handled, which is a strong reason to list variants explicitly when matching on your own enums. Here a catch-all is the right answer, because nothing guarantees that a logged status falls inside the five standard ranges:

src/main.rs
            500..=599 => StatusClass::ServerError,
            _ => StatusClass::Other,

A method, a function that works on a value of the type, takes &self, a shared reference to that value. It is called with a dot: entry.class().

src/main.rs
impl Entry {
    fn class(&self) -> StatusClass {
        StatusClass::from_code(self.status)
    }
}

Parsing a line by hand

split_once splits a string at the first occurrence of a separator. It returns Option<(&str, &str)>: the text before and after the separator, or None if the separator does not occur. Taking the address off the front of a line looks like this:

src/main.rs
    let (addr, rest) = match line.split_once(' ') {
        Some(pair) => pair,
        None => return None,
    };

match is an expression. The first arm evaluates to the pair inside Some, which the let destructures into two variables. The second arm leaves the function. This shape, take the value or bail out, occurs so often that it has a shorter form:

src/main.rs
    let Some((_, rest)) = rest.split_once('"') else {
        return None;
    };

let ... else binds the variables in the pattern if the value matches. Otherwise it runs the else block, which must leave the enclosing function or loop. _ ignores part of a pattern. Declaring rest a second time is called shadowing: a new variable takes over the name, which suits a value that is narrowed step by step.

The whole parser:

src/main.rs
fn parse_line(line: &str) -> Option<Entry> {
    let (addr, rest) = match line.split_once(' ') {
        Some(pair) => pair,
        None => return None,
    };

    // The request is the first double-quoted field.
    let Some((_, rest)) = rest.split_once('"') else {
        return None;
    };
    let Some((request, rest)) = rest.split_once('"') else {
        return None;
    };

    // "GET /index.html HTTP/1.1": the path is the second word.
    let mut words = request.split_whitespace();
    let Some(_method) = words.next() else {
        return None;
    };
    let Some(path) = words.next() else {
        return None;
    };

    // After the request: status, then size ("-" when no body was sent).
    let mut fields = rest.split_whitespace();
    let Some(status) = fields.next() else {
        return None;
    };
    let Ok(status) = status.parse::<u16>() else {
        return None;
    };
    let bytes = match fields.next() {
        Some("-") => None,
        Some(text) => {
            let Ok(n) = text.parse::<u64>() else {
                return None;
            };
            Some(n)
        }
        None => return None,
    };

    Some(Entry {
        addr: addr.to_string(),
        path: path.to_string(),
        status,
        bytes,
    })
}

split_whitespace returns an iterator over the words of a string, and each call to next() returns an Option holding the following word. status.parse::<u16>() converts text to a number and returns a Result, the subject of the next lesson; for now, read Ok(status) as a pattern like Some(status). The final match shows that patterns nest: Some("-") matches that exact string, Some(text) matches any other and binds it, and None covers a missing field.

The parser treats the first two double quotes as the limits of the request. That is exact for nginx, whose default escaping writes a quote inside a logged value as \x22. Apache writes it as \", so a request containing a quote fails to parse there and is counted as a skipped line. For a summary tool that is an acceptable loss, and a known one.

Using the entries

With a parser in place, client_addr and remember from lesson 2 can be deleted, and main works on entries:

src/main.rs
fn main() {
    let mut requests = 0;
    let mut skipped = 0;
    let mut bytes = 0;

    for path in env::args().skip(1) {
        let contents = fs::read_to_string(&path).expect("could not read file");
        for line in contents.lines() {
            let Some(entry) = parse_line(line) else {
                skipped += 1;
                continue;
            };

            requests += 1;
            if let Some(n) = entry.bytes {
                bytes += n;
            }
            match entry.class() {
                StatusClass::ClientError | StatusClass::ServerError => {
                    println!("{} {} from {}", entry.status, entry.path, entry.addr);
                }
                _ => {}
            }
        }
    }

    println!("{requests} requests, {skipped} lines skipped, {bytes} bytes");
}

Each pattern form is used where it fits. let ... else deals with a line that failed to parse by counting it and moving to the next one. if let runs its block only when the pattern matches, which suits bytes: add the size if there is one, do nothing otherwise. The match on the class uses | to give two variants the same arm, and _ for the rest.

cargo run -q -- access.log
404 /favicon.ico from 203.0.113.7
500 /api/orders from 192.0.2.44
403 /admin from 192.0.2.44
404 /favicon.ico from 2001:db8::1f
502 /api/orders from 198.51.100.23
16 requests, 2 lines skipped, 152631 bytes

The two damaged lines are now recognized as such.

Moving the parser into a module

main.rs has reached 118 lines and holds two unrelated things: the model of a log line and the program around it. Create src/entry.rs and move Entry, StatusClass, both impl blocks and parse_line into it. Then declare the module at the top of main.rs:

src/main.rs
mod entry;

use std::env;
use std::fs;

use entry::{StatusClass, parse_line};

mod entry; tells the compiler that src/entry.rs belongs to the crate, as a module named entry. A file that no mod line mentions is not compiled at all. The use line then imports the two names main refers to.

Everything in a module is private to it by default, so the build fails, with one error for each name that main.rs imports:

error[E0603]: enum `StatusClass` is private
  --> src/main.rs:6:13
   |
 6 | use entry::{StatusClass, parse_line};
   |             ^^^^^^^^^^^ private enum
   |
note: the enum `StatusClass` is defined here
  --> src/entry.rs:10:1
   |
10 | enum StatusClass {
   | ^^^^^^^^^^^^^^^^
...

Add pub to the struct, to each of its fields, to the enum and to the three functions. Variants of a public enum are public automatically. Struct fields are not, so that a type can expose itself while keeping its insides to its own module.

src/entry.rs
#[derive(Debug)]
pub struct Entry {
    pub addr: String,
    pub path: String,
    pub status: u16,
    pub bytes: Option<u64>,
}

With the pub keywords in place, the program builds and prints the same output as before.

parse_line can say that a line is bad but not why, and main still panics when a file is missing. The next lesson gives both failures a type.

Exercises

  1. Add a method is_error(self) -> bool to StatusClass, written as a match on self with one arm per variant and no _, and use it in main in place of the match. Then add a seventh variant to the enum for a moment. The compiler should reject is_error with E0004 and name the variant you added.
  2. Add the request method to Entry as a String and include it in the output. The first line printed for the sample file should be 404 GET /favicon.ico from 203.0.113.7.
  3. Print every parsed entry with println!("{entry:?}"). The first line of output should be Entry { addr: "203.0.113.7", path: "/", status: 200, bytes: Some(5123) }. Change {entry:?} to {entry:#?} and compare.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are