Rust Playbook

Course › Week 1 · Basics and ownership › Day 5 · lesson 5 of 42 · 25 min reading + 60–90 min practice

Structs, enums and match

Your own types: a struct with methods, an enum that carries data, Option instead of null, and match.

structimplenummatchOptionif let

On this page
  1. 1. A struct groups named fields
  2. 2. impl: functions and methods for a type
  3. 3. An enum is one of a fixed set
  4. 4. match: every case, checked
  5. 5. An enum variant can carry data
  6. 6. Option: a value or nothing, never null
  7. Coming from PHP
  8. Practice
  9. Remember

Today you make your own types, and all of them are about tomorrow’s tool: a log line, its level, and what to do when a line is not a log line at all.

Six ideas, in order: a struct, methods on it, an enum, match, an enum that carries data, and Option, Rust’s replacement for null. The last one is the most important.

1. A struct groups named fields

A struct is a type with named fields, each with its own type. Think of a PHP class with only typed public properties and no methods yet.

src/main.rs
struct LogEntry {
    timestamp: String,
    level: String,
    message: String,
}

fn main() {
    let entry = LogEntry {
        timestamp: String::from("2026-11-30 14:02:11"),
        level: String::from("ERROR"),
        message: String::from("Payment failed"),
    };

    println!("{} [{}] {}", entry.timestamp, entry.level, entry.message);
}
$ cargo run
2026-11-30 14:02:11 [ERROR] Payment failed

There is no new keyword. You build a struct by naming every field; leave one out and it does not compile.

Printing a whole struct needs Debug

{:?} prints a value for debugging, like var_dump. A struct does not support it until you ask:

src/main.rsdoes not compile
struct LogEntry {
    level: String,
    message: String,
}

fn main() {
    let entry = LogEntry {
        level: String::from("ERROR"),
        message: String::from("Payment failed"),
    };
    println!("{entry:?}");
}
cargo build
error[E0277]: `LogEntry` doesn't implement `Debug`
  --> src/main.rs:11:15
   |
11 |     println!("{entry:?}");
   |               ^^^^^^^^^ `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 {
   |

For more information about this error, try `rustc --explain E0277`.
error: could not compile `hello` (bin "hello") due to 1 previous error

The help: gives the fix: put #[derive(Debug)] above the struct. derive asks the compiler to write the code for you. You will derive more things in Week 2.

src/main.rs
#[derive(Debug)]
struct LogEntry {
    level: String,
    message: String,
}

fn main() {
    let entry = LogEntry {
        level: String::from("ERROR"),
        message: String::from("Payment failed"),
    };
    println!("{entry:?}");
    println!("{entry:#?}"); // pretty: one field per line
}
cargo build
warning: fields `level` and `message` are never read
 --> src/main.rs:3:5
  |
2 | struct LogEntry {
  |        -------- fields in this struct
3 |     level: String,
  |     ^^^^^
4 |     message: String,
  |     ^^^^^^^
  |
  = note: `LogEntry` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
  = note: `#[warn(dead_code)]` (part of `#[warn(unused)]`) on by default
$ cargo run
LogEntry { level: "ERROR", message: "Payment failed" }
LogEntry {
    level: "ERROR",
    message: "Payment failed",
}

It builds and runs, with a warning first. Rust warns about code that is never used, and printing with {:?} does not count as reading a field. Warnings never stop the build, but in this course they are treated like errors: code you ship has none. Here it goes away as soon as the program reads entry.level somewhere.

2. impl: functions and methods for a type

Functions for a type go in an impl block. A function without self is called with ::, like a PHP static method; by convention, new is the constructor. A function with &self is a method, called with a dot, and it borrows the value it is called on.

src/main.rs
struct LogEntry {
    level: String,
    message: String,
}

impl LogEntry {
    fn new(level: &str, message: &str) -> LogEntry {
        LogEntry {
            level: level.to_string(),
            message: message.to_string(),
        }
    }

    fn is_error(&self) -> bool {
        self.level == "ERROR"
    }

    fn shout(&mut self) {
        self.message = self.message.to_uppercase();
    }
}

fn main() {
    let mut entry = LogEntry::new("ERROR", "Payment failed");
    entry.shout();

    println!("{} (error: {})", entry.message, entry.is_error());
}
$ cargo run
PAYMENT FAILED (error: true)

&self reads, &mut self changes, exactly the borrowing rules from Day 4. .to_string() turns a &str into an owned String (it copies the text).

Inside impl LogEntry, you can write Self instead of LogEntry. You will see fn new(…) -> Self everywhere in real code.

3. An enum is one of a fixed set

Storing the level as a String lets anything in: "EROR", "error", "". An enum lists the only values a type can have. Laravel’s log levels come from Monolog, and there are eight:

src/main.rs
#[derive(Debug)]
#[allow(dead_code)] // this example only creates one of the levels; without this line, Rust warns about the other seven
enum Level {
    Debug,
    Info,
    Notice,
    Warning,
    Error,
    Critical,
    Alert,
    Emergency,
}

fn main() {
    let level = Level::Error;
    println!("{level:?}");
}
$ cargo run
Error

#[allow(dead_code)] switches off the “never used” warning for that one enum. Small examples on this site use it when they define more than they use; real code rarely needs it.

4. match: every case, checked

match compares a value against patterns, top to bottom, and runs the first that fits. Like if, it is an expression, so it produces a value. | means “or”.

src/main.rs
#[allow(dead_code)]
enum Level {
    Debug,
    Info,
    Notice,
    Warning,
    Error,
    Critical,
    Alert,
    Emergency,
}

fn needs_attention(level: &Level) -> bool {
    match level {
        Level::Debug | Level::Info | Level::Notice => false,
        Level::Warning | Level::Error | Level::Critical | Level::Alert | Level::Emergency => true,
    }
}

fn main() {
    println!("{}", needs_attention(&Level::Info));
    println!("{}", needs_attention(&Level::Critical));
}
$ cargo run
false
true

Forget a case and it does not compile

This is the reason to use match. Leave out a level, and the compiler lists exactly which ones are missing:

src/main.rsdoes not compile
enum Level {
    Debug,
    Info,
    Notice,
    Warning,
    Error,
    Critical,
    Alert,
    Emergency,
}

fn needs_attention(level: &Level) -> bool {
    match level {
        Level::Debug | Level::Info | Level::Notice => false,
        Level::Warning | Level::Error => true,
    }
}

fn main() {
    println!("{}", needs_attention(&Level::Alert));
}
cargo build
error[E0004]: non-exhaustive patterns: `&Level::Critical`, `&Level::Alert` and `&Level::Emergency` not covered
  --> src/main.rs:13:11
   |
13 |     match level {
   |           ^^^^^ patterns `&Level::Critical`, `&Level::Alert` and `&Level::Emergency` not covered
   |
note: `Level` defined here
  --> src/main.rs:1:6
   |
 1 | enum Level {
   |      ^^^^^
...
 7 |     Critical,
   |     -------- not covered
 8 |     Alert,
   |     ----- not covered
 9 |     Emergency,
   |     --------- not covered
   = note: the matched value is of type `&Level`
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
   |
15 ~         Level::Warning | Level::Error => true,
16 ~         &Level::Critical | &Level::Alert | &Level::Emergency => todo!(),
   |

For more information about this error, try `rustc --explain E0004`.
error: could not compile `hello` (bin "hello") due to 1 previous error

Months later, someone adds a ninth level to the enum: every match that forgot about it stops compiling, and the compiler lists each one. In PHP the same mistake is found by a user, at runtime.

_ => … matches anything that is left, like default. Use it sparingly: it switches this protection off for every case it swallows.

5. An enum variant can carry data

Each variant can hold its own fields. match takes them out by name. This has no direct PHP equivalent, and Rust code uses it everywhere:

src/main.rs
enum Line {
    Entry { level: String, message: String },
    StackTrace(String),
    Blank,
}

fn describe(line: &Line) -> String {
    match line {
        Line::Entry { level, message } => format!("{level}: {message}"),
        Line::StackTrace(text) => format!("  (trace) {text}"),
        Line::Blank => String::from("(blank)"),
    }
}

fn main() {
    let lines = [
        Line::Entry {
            level: String::from("ERROR"),
            message: String::from("Payment failed"),
        },
        Line::StackTrace(String::from("#0 app/Services/Stripe.php(41)")),
        Line::Blank,
    ];

    for line in &lines {
        println!("{}", describe(line));
    }
}
$ cargo run
ERROR: Payment failed
  (trace) #0 app/Services/Stripe.php(41)
(blank)

format! works like println! but returns the text as a String instead of printing it. for line in &lines loops over the array by reference, so the array is not moved into the loop.

6. Option: a value or nothing, never null

Option is an enum

Rust has no null. When a value may be missing, its type says so: Option<Level> is either Some(level) or None. It is a plain enum from the standard library, always available:

what the standard library defines
enum Option<T> {
    Some(T),
    None,
}

<T> means “any type”: Option<Level>, Option<u64>, Option<String>. Week 2 covers how that works; today, read it as “an optional Level”.

Parsing returns an Option

Text from a log file might not be a level at all. So the parser returns Option<Level>, and matching on a &str handles each known name:

src/main.rs
#[derive(Debug)]
enum Level {
    Debug,
    Info,
    Notice,
    Warning,
    Error,
    Critical,
    Alert,
    Emergency,
}

fn parse_level(name: &str) -> Option<Level> {
    match name {
        "DEBUG" => Some(Level::Debug),
        "INFO" => Some(Level::Info),
        "NOTICE" => Some(Level::Notice),
        "WARNING" => Some(Level::Warning),
        "ERROR" => Some(Level::Error),
        "CRITICAL" => Some(Level::Critical),
        "ALERT" => Some(Level::Alert),
        "EMERGENCY" => Some(Level::Emergency),
        _ => None,
    }
}

fn main() {
    println!("{:?}", parse_level("ERROR"));
    println!("{:?}", parse_level("EROR"));
}
$ cargo run
Some(Error)
None

Here _ => None is right: there are endless strings that are not levels.

You cannot use an Option as if it were the value

In PHP, a function that returns ?Level hands you null, and the crash comes later, wherever you use it. Rust does not let you skip the check:

src/main.rsdoes not compile
enum Level {
    Info,
    Error,
}

fn parse_level(name: &str) -> Option<Level> {
    match name {
        "INFO" => Some(Level::Info),
        "ERROR" => Some(Level::Error),
        _ => None,
    }
}

fn main() {
    let level: Level = parse_level("ERROR");
}
cargo build
error[E0308]: mismatched types
  --> src/main.rs:15:24
   |
15 |     let level: Level = parse_level("ERROR");
   |                -----   ^^^^^^^^^^^^^^^^^^^^ expected `Level`, found `Option<Level>`
   |                |
   |                expected due to this
   |
   = note: expected enum `Level`
              found enum `Option<Level>`
help: consider using `Option::expect` to unwrap the `Option<Level>` value, panicking if the value is an `Option::None`
   |
15 |     let level: Level = parse_level("ERROR").expect("REASON");
   |                                            +++++++++++++++++

For more information about this error, try `rustc --explain E0308`.
error: could not compile `hello` (bin "hello") due to 1 previous error

Three ways to handle it

match handles both cases. if let is shorter when you only care about Some. And let … else takes the value out, or leaves the function when it is missing: the cleanest shape for “stop here if this is not what I expected”.

src/main.rs
#[derive(Debug)]
enum Level {
    Info,
    Error,
}

fn parse_level(name: &str) -> Option<Level> {
    match name {
        "INFO" => Some(Level::Info),
        "ERROR" => Some(Level::Error),
        _ => None,
    }
}

fn report(name: &str) {
    let Some(level) = parse_level(name) else {
        println!("{name}: not a level, skipped");
        return;
    };
    println!("{name}: {level:?}");
}

fn main() {
    match parse_level("INFO") {
        Some(level) => println!("match: {level:?}"),
        None => println!("match: not a level"),
    }

    if let Some(level) = parse_level("ERROR") {
        println!("if let: {level:?}");
    }

    report("ERROR");
    report("EROR");
}
$ cargo run
match: Info
if let: Error
ERROR: Error
EROR: not a level, skipped

The else block of let … else must leave: return, break, continue, or end the program. Tomorrow’s tool uses it on every line of the log.

Yesterday’s exercise used .unwrap(): it takes the value out of Some, and panics on None. That is acceptable in a quick experiment and in tests, never in a tool you ship.

Coming from PHP

PHP 8.1 enums and match are close relatives. The differences are where Rust checks earlier.

Level.php
<?php

enum Level: string
{
    case Error = 'ERROR';
    case Info = 'INFO';
}

$level = Level::tryFrom('EROR');    // ?Level: null, and nothing makes you check

$attention = match ($level) {
    Level::Error => true,
    // Level::Info forgotten: UnhandledMatchError, at runtime, on the first INFO line
};

tryFrom returning ?Level is Rust’s Option<Level> without the enforcement. A missing match arm in PHP throws when that case finally happens; in Rust the program does not build. And PHP enum cases cannot carry their own fields, which is what section 5 used.

PracticeThe Book ch. 5–6, Rustlings structs, enums, options

Read chapter 5 and chapter 6 of the Book.

In Rustlings: 07_structs, 08_enums, and 12_options 1 and 2.

Exercise: a parsed line

Write fn parse_line(line: &str) -> Option<Entry> where Entry is a struct with level: Level and message: String. A line is [YYYY-MM-DD HH:MM:SS] env.LEVEL: message. Return None when the line does not start with [, or when the level is unknown. Use let … else, and .find(), which returns an Option<usize> itself.

Test it on a good line, a stack-trace line (#0 app/Services/Stripe.php(41)) and a line with an unknown level.

Show the solution
src/main.rs
#[derive(Debug)]
enum Level {
    Info,
    Warning,
    Error,
}

struct Entry {
    level: Level,
    message: String,
}

fn parse_level(name: &str) -> Option<Level> {
    match name {
        "INFO" => Some(Level::Info),
        "WARNING" => Some(Level::Warning),
        "ERROR" => Some(Level::Error),
        _ => None,
    }
}

fn parse_line(line: &str) -> Option<Entry> {
    if !line.starts_with('[') {
        return None;
    }
    let Some(close) = line.find("] ") else {
        return None;
    };
    let rest = &line[close + 2..]; // "production.ERROR: Payment failed"
    let Some(dot) = rest.find('.') else {
        return None;
    };
    let Some(colon) = rest.find(": ") else {
        return None;
    };
    let Some(level) = parse_level(&rest[dot + 1..colon]) else {
        return None;
    };
    Some(Entry {
        level,
        message: rest[colon + 2..].to_string(),
    })
}

fn main() {
    let lines = [
        "[2026-11-30 14:02:11] production.ERROR: Payment failed",
        "#0 app/Services/Stripe.php(41)",
        "[2026-11-30 14:02:11] production.SHOUTING: hello",
    ];

    for line in lines {
        match parse_line(line) {
            Some(entry) => println!("{:?}: {}", entry.level, entry.message),
            None => println!("skipped: {line}"),
        }
    }
}
cargo clippy --message-format=short
src/main.rs:26:5: warning: this `let...else` may be rewritten with the `?` operator: help: replace it with: `let close = line.find("] ")?;`
src/main.rs:30:5: warning: this `let...else` may be rewritten with the `?` operator: help: replace it with: `let dot = rest.find('.')?;`
src/main.rs:33:5: warning: this `let...else` may be rewritten with the `?` operator: help: replace it with: `let colon = rest.find(": ")?;`
src/main.rs:36:5: warning: this `let...else` may be rewritten with the `?` operator: help: replace it with: `let level = parse_level(&rest[dot + 1..colon])?;`
$ cargo run
Error: Payment failed
skipped: #0 app/Services/Stripe.php(41)
skipped: [2026-11-30 14:02:11] production.SHOUTING: hello

Entry { level, message: … }: when a variable has the same name as the field, you write it once.

It works. Now run clippy on it. It has the same suggestion for each let … else that only returns None (the --message-format=short flag prints one line per warning):

The ? operator, on an Option

RuleInside a function that returns an Option, value? means: if it is None, return None right now; otherwise, take what is inside.

Each four-line let … else becomes one line. The behaviour is exactly the same, and this is how real Rust code reads. In Week 2 you will use the same ? on Result, where it passes the error up instead of None.

src/main.rs
#[derive(Debug)]
enum Level {
    Info,
    Warning,
    Error,
}

struct Entry {
    level: Level,
    message: String,
}

fn parse_level(name: &str) -> Option<Level> {
    match name {
        "INFO" => Some(Level::Info),
        "WARNING" => Some(Level::Warning),
        "ERROR" => Some(Level::Error),
        _ => None,
    }
}

fn parse_line(line: &str) -> Option<Entry> {
    if !line.starts_with('[') {
        return None;
    }
    let close = line.find("] ")?;
    let rest = &line[close + 2..]; // "production.ERROR: Payment failed"
    let dot = rest.find('.')?;
    let colon = rest.find(": ")?;
    let level = parse_level(&rest[dot + 1..colon])?;
    Some(Entry {
        level,
        message: rest[colon + 2..].to_string(),
    })
}

fn main() {
    let lines = [
        "[2026-11-30 14:02:11] production.ERROR: Payment failed",
        "#0 app/Services/Stripe.php(41)",
        "[2026-11-30 14:02:11] production.SHOUTING: hello",
    ];

    for line in lines {
        match parse_line(line) {
            Some(entry) => println!("{:?}: {}", entry.level, entry.message),
            None => println!("skipped: {line}"),
        }
    }
}
$ cargo run
Error: Payment failed
skipped: #0 app/Services/Stripe.php(41)
skipped: [2026-11-30 14:02:11] production.SHOUTING: hello

Use let … else when the else does something more than return None, like printing a message or exiting, as in tomorrow’s main. Use ? when it would only pass the None on.

Remember

  • A fixed set of values is an enum, and a match on it must handle every case; avoid _ when the cases are known.
  • A value that may be missing is an Option: handle it with match, if let, let … else, or pass it on with ?.

Tomorrow you build logstat v1: a real command-line tool that reads a laravel.log and counts its entries by level.