Skip to content

cat posts/en/rust-lernen-05-structs.md

Learning Rust (Part 5): Structs and methods

Custom types with struct, methods with impl, and the three forms of self. logbuch now splits each line into a LogEntry only once and analyzes the log in a single pass.

Macro photo: Side by side in an egg carton sit a brown egg, a speckled egg, a golf ball, a chocolate egg in a gold candy cup, and a tomato.

So far, logbuch (German for logbook) runs over the text three times: zaehle_zeilen counts, zaehle_fehler and fehlerbericht split every line for the status code, and fehlerbericht splits error lines once more for the path. This time, everything a line contains goes into a type of its own. The first attempt to print it (eintrag is German for entry):

struct LogEntry {
    ip: String,
    status: u16,
}

fn main() {
    let eintrag = LogEntry {
        ip: String::from("192.0.2.44"),
        status: 404,
    };
    println!("{eintrag}");
}
error[E0277]: `LogEntry` doesn't implement `std::fmt::Display`
  --> src/main.rs:11:15
   |
11 |     println!("{eintrag}");
   |               ^^^^^^^^^ `LogEntry` cannot be formatted with the default formatter
   |
help: the trait `std::fmt::Display` is not implemented for `LogEntry`
  --> src/main.rs:1:1
   |
 1 | struct LogEntry {
   | ^^^^^^^^^^^^^^^
   = note: in format strings you may be able to use `{:?}` (or `{:#?}` for pretty-print) instead

Python prints any object somehow, as <__main__.LogEntry object at 0x7f…> if nothing else works. Rust prints nothing unless it knows what it's supposed to look like. The suggested {:?} leads to the next error:

error[E0277]: `LogEntry` doesn't implement `Debug`
  --> src/main.rs:11:15
   |
11 |     println!("{eintrag:?}");
   |               ^^^^^^^^^^^ `LogEntry` cannot be formatted using `{:?}` because it doesn't implement `Debug`
   |
   = help: the trait `Debug` is not implemented for `LogEntry`
help: consider annotating `LogEntry` with `#[derive(Debug)]`
   |
 1 + #[derive(Debug)]
 2 | struct LogEntry {
   |

logbuch takes up that suggestion in a moment. First, the type itself.

A type of your own

struct defines a struct: a type with named fields, each with a fixed type. The complete LogEntry for logbuch (methode and pfad are German for method and path):

#[derive(Debug, PartialEq)]
struct LogEntry {
    ip: String,
    methode: String,
    pfad: String,
    status: u16,
    bytes: u64,
}

The closest thing in Python is a dataclass. A struct's definition contains only data, though. Methods go separately into an impl block, and Rust has no inheritance at all. Part 10planned covers behavior shared by several types.

You create a value by specifying every field:

let eintrag = LogEntry {
    ip: String::from("192.0.2.44"),
    methode: String::from("POST"),
    pfad: String::from("/wp-login.php"),
    status: 404,
    bytes: 153,
};
println!("{}", eintrag.status);

Leaving out a field is a compiler error; there are no default values like field(default=...). You access the fields with a dot, as in Python.

Why String and not &str

So far, logbuch has used slices of the line so it wouldn't copy anything. A field of type &str fails, though:

error[E0106]: missing lifetime specifier
 --> src/main.rs:2:9
  |
2 |     ip: &str,
  |         ^ expected named lifetime parameter
  |
help: consider introducing a named lifetime parameter
  |
1 ~ struct LogEntry<'a> {
2 ~     ip: &'a str,
  |

A struct with references must not outlive the text they point to, and that has to be stated in the type. Part 9planned shows how. Until then, LogEntry owns its fields as Strings. That costs one copy per text field and line, but it makes the type independent of the line it came from.

derive

#[derive(Debug, PartialEq)] in front of the struct has the compiler generate code: Debug for output with {:?}, PartialEq for comparison with ==. That matches what @dataclass does with __repr__ and __eq__ (the article on dunder methods explains what's behind them):

LogEntry { ip: "203.0.113.7", methode: "GET", pfad: "/", status: 200, bytes: 5123 }

With {:#?}, each field goes on its own line, which is handy for large structs.

Debug, PartialEq, and Display are traits: capabilities a type either has or doesn't. For Debug and PartialEq, derive is enough. Display, the output with {}, you have to write yourself, because the compiler can't know what a LogEntry should look like to humans. That comes in part 10planned.

Methods

Methods go in an impl block for the type (aus_zeile is German for from line, felder for fields, ist_fehler for is_error):

impl LogEntry {
    fn aus_zeile(zeile: &str) -> LogEntry {
        let mut felder = zeile.split_whitespace();
        let ip = felder.next().expect("Line without IP");
        let methode = felder.nth(4).expect("Line without method");
        let pfad = felder.next().expect("Line without path");
        let status = felder.nth(1).expect("Line without status code");
        let bytes = felder.next().expect("Line without bytes");

        LogEntry {
            ip: ip.to_string(),
            methode: methode[1..].to_string(),
            pfad: pfad.to_string(),
            status: status.parse().expect("Status code is not a number"),
            bytes: bytes.parse().expect("Bytes are not a number"),
        }
    }

    fn ist_fehler(&self) -> bool {
        self.status >= 400
    }
}

aus_zeile has no self. That makes it an associated function, something like a @classmethod in Python, and you call it through the type: LogEntry::aus_zeile(zeile). There's no constructor in the sense of __init__. The convention is an associated function named new or, as here, one whose name says what the value is made from.

The line now gets split only once. felder is an iterator that remembers how far it has gotten. That's why it needs mut, and that's why nth counts from the current position: after the IP, nth(4) skips the four fields -, -, timestamp, and time zone and returns the method. methode[1..] cuts off the quotation mark, as in exercise 3 of part 4. .to_string() turns each slice into a String of its own.

ist_fehler, on the other hand, takes &self, so it's a method in the narrower sense, and you call it on a value: eintrag.ist_fehler(). As in Python, self appears explicitly in the parameter list. What's new is that the parameter also says how the method receives the value, and those are exactly the three cases from parts 3 and 4:

  • &self borrows the value for reading.
  • &mut self borrows it for changing.
  • self takes it over. After that, the value is gone for the caller.

Python doesn't make this distinction. Any method there can do whatever it likes with self.

The analysis

The second new type collects what used to be spread across three functions. Two new things come along: the total number of bytes and the method in every report line (Auswertung is German for analysis, zeilen for lines, fehler for errors, bericht for report, erfasse for record, fehleranteil for error share):

struct Auswertung {
    zeilen: usize,
    fehler: usize,
    bytes: u64,
    bericht: String,
}

impl Auswertung {
    fn new() -> Auswertung {
        Auswertung {
            zeilen: 0,
            fehler: 0,
            bytes: 0,
            bericht: String::new(),
        }
    }

    fn erfasse(&mut self, eintrag: &LogEntry) {
        self.zeilen += 1;
        self.bytes += eintrag.bytes;
        if eintrag.ist_fehler() {
            self.fehler += 1;
            let pfad = ohne_query(&eintrag.pfad);
            self.bericht.push_str(&format!(
                "  {} {} {pfad}\n",
                eintrag.status, eintrag.methode
            ));
        }
    }

    fn fehleranteil(&self) -> f64 {
        if self.zeilen == 0 {
            0.0
        } else {
            self.fehler as f64 / self.zeilen as f64 * 100.0
        }
    }
}

erfasse changes the analysis and therefore needs &mut self. fehleranteil only reads. In the format string, eintrag.status and eintrag.methode come after the string, because only variable names are allowed inside the curly braces, not field access.

That makes main short (auswerten is German for analyze):

fn main() {
    let pfad = env::args().nth(1).expect("Usage: logbuch <FILE>");
    let text = fs::read_to_string(&pfad).expect("Couldn't read file");

    let auswertung = auswerten(&text);
    println!(
        "{pfad}: {} lines, {} bytes, {} errors ({:.1} %)",
        auswertung.zeilen,
        auswertung.bytes,
        auswertung.fehler,
        auswertung.fehleranteil()
    );
    print!("{}", auswertung.bericht);
}

fn auswerten(text: &str) -> Auswertung {
    let mut auswertung = Auswertung::new();
    for zeile in text.lines() {
        let eintrag = LogEntry::aus_zeile(zeile);
        auswertung.erfasse(&eintrag);
    }
    auswertung
}

One loop instead of three, and every line gets split exactly once. Of the previous functions, only ohne_query from part 4 remains. zaehle_zeilen, zaehle_fehler, fehlerbericht, ergaenze, anfrage_pfad, and statuscode go away, along with their tests and, if you adopted it, methode from exercise 3 of part 4.

Tests

New tests check the types directly:

    #[test]
    fn liest_alle_felder() {
        let erwartet = LogEntry {
            ip: String::from("192.0.2.44"),
            methode: String::from("POST"),
            pfad: String::from("/wp-login.php"),
            status: 404,
            bytes: 153,
        };
        assert_eq!(LogEntry::aus_zeile(ZEILE_404), erwartet);
    }

    #[test]
    fn erkennt_fehler() {
        assert!(LogEntry::aus_zeile(ZEILE_404).ist_fehler());
        assert!(!LogEntry::aus_zeile(ZEILE_200).ist_fehler());
    }

    #[test]
    fn wertet_text_aus() {
        let text = format!("{ZEILE_200}\n{ZEILE_404}\n");
        let auswertung = auswerten(&text);
        assert_eq!(auswertung.zeilen, 2);
        assert_eq!(auswertung.fehler, 1);
        assert_eq!(auswertung.bytes, 5276);
        assert_eq!(auswertung.bericht, "  404 POST /wp-login.php\n");
        assert_eq!(auswertung.fehleranteil(), 50.0);
    }

    #[test]
    fn leerer_text() {
        let auswertung = auswerten("");
        assert_eq!(auswertung.zeilen, 0);
        assert_eq!(auswertung.fehleranteil(), 0.0);
    }

    #[test]
    #[should_panic(expected = "Line without method")]
    fn kaputte_zeile_bricht_ab() {
        LogEntry::aus_zeile("not a log line");
    }

assert! checks a single boolean, like assert in Python. liest_alle_felder compares two complete LogEntry values. That only works thanks to PartialEq. Without PartialEq in the derive, the compiler reports:

error[E0369]: binary operation `==` cannot be applied to type `LogEntry`
   --> src/main.rs:120:9
    |
120 |         assert_eq!(LogEntry::aus_zeile(ZEILE_404), erwartet);
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |         |
    |         LogEntry
    |         LogEntry
    |
note: an implementation of `PartialEq` might be missing for `LogEntry`
...
help: consider annotating `LogEntry` with `#[derive(PartialEq)]`

assert_eq! also needs Debug so it can show both values when the test fails.

The test for malformed lines now expects “Line without method” instead of “Line without status code.” “not a log line” has only four fields, and aus_zeile reads the method before the status code. With the old expectation, the test fails, and cargo test shows both texts:

note: panic did not contain expected string
      panic message: "Line without method"
 expected substring: "Line without status code"

With everything in place:

$ cargo test
...
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
$ cargo run -- access.log
...
access.log: 5 lines, 48642 bytes, 2 errors (40.0 %)
  404 GET /favicon.ico
  404 POST /wp-login.php

The sixth test is schneidet_query_ab from part 4, unchanged.

Exercises

1. Why doesn't this compile? In auswerten, accidentally write let auswertung = Auswertung::new(); without mut. What does the compiler report, and why at the line with erfasse, of all places?

Solution
error[E0596]: cannot borrow `auswertung` as mutable, as it is not declared as mutable
  --> src/main.rs:94:9
   |
94 |         auswertung.erfasse(&eintrag);
   |         ^^^^^^^^^^ cannot borrow as mutable
   |
help: consider changing this to be mutable
   |
91 |     let mut auswertung = Auswertung::new();
   |         +++
`erfasse` takes `&mut self`. So the call `auswertung.erfasse(…)` borrows `&mut auswertung`, and that only works with a variable declared `mut`. Rust inserts the `&mut` itself in a method call, which is why it doesn't appear in the code, but it still gets checked.

2. Used up. Write a method fn in_bericht(self) -> String that returns only the report. What happens if you print auswertung.zeilen after let bericht = auswertung.in_bericht();?

Solution
fn in_bericht(self) -> String {
    self.bericht
}
After that, `auswertung` is gone:
error[E0382]: borrow of moved value: `auswertung`
...
note: `Auswertung::in_bericht` takes ownership of the receiver `self`, which moves `auswertung`
`self` without `&` takes over the value. The method hands out the `bericht` field, and the rest of the analysis is freed. That makes sense when a value isn't needed anymore after the call, and it saves the copy that a `self.bericht.clone()` would cost.

3. A type for the status code. Besides structs with named fields, there are tuple structs without field names: struct Statuscode(u16);. Write a method klasse for it (German for class) that returns 4 for 404.

Solution
struct Statuscode(u16);

impl Statuscode {
    fn klasse(&self) -> u16 {
        self.0 / 100
    }
}
`self.0` is the first field, as with a tuple. A tuple struct with a single field gives a number a type of its own: a function that expects a `Statuscode` won't accept just any `u16`. That costs nothing at runtime; `Statuscode` is exactly as big as a `u16`.

Next up

methode is a String, even though there are only a handful of valid values: GET, POST, HEAD, and a few more. In part 6planned, it becomes an enum, and match makes sure logbuch doesn't forget a case. On top of that, part 6 finally gets to the container that nth, next, and find return: Option.

0 comments

No comments yet. Be the first!