Skip to main content

IndexRustTutorial

Rust Structs, Enums and Pattern Matching for JS Devs

Part 4 of Rust for web developers: structs and methods, enums that carry data, exhaustive match, if let and let-else, compared to TypeScript unions.

By LearnWebCraft Team24 min readBeginner

Part 4 of 15 · Rust for web developers

Up to now, every piece of data we've handled has been a built-in type: numbers, strings, tuples, vectors and a hash map. Real programs need their own types. A web backend has users, orders, sessions, payment states and request types, and how you model them decides how many bugs you can even write.

This part covers the two ways Rust lets you define types. Structs group related fields together, which you'll find familiar from TypeScript interfaces and classes. Enums are where Rust gets interesting. A Rust enum isn't a list of named constants like a TypeScript enum. Each variant can carry its own data, which makes it the same idea as a TypeScript discriminated union, except the compiler enforces it far more strictly. Add match, which checks you've handled every case, and you get one of the habits Rust developers miss most when they go back to other languages: making invalid states impossible to write down.

All examples were run with Rust 1.100.0, and every output and error below is copied from those runs. If you haven't read part 3 on ownership, do that first, because methods borrow self in exactly the ways it describes.

Structs

Defining and creating one

Fig. 1rust
#[derive(Debug, Clone, PartialEq)]
struct User {
    id: u64,
    email: String,
    name: String,
    active: bool,
}

A struct is a named group of fields, each with a type. Ignore the #[derive(...)] line for a moment, we'll come back to it.

In TypeScript you'd write the shape as an interface:

Fig. 2ts
interface User {
  id: number;
  email: string;
  name: string;
  active: boolean;
}

The difference that matters: a TypeScript interface only describes a shape, and any object that happens to match it is a User. A Rust struct is a real, distinct type. Two structs with identical fields are still different types, and you can't pass one where the other is expected. This is called nominal typing, and it's what lets Rust tell a UserId from an OrderId even when both are just numbers inside.

Creating one, you must set every field:

Fig. 3rustRun
struct User {
    id: u64,
    email: String,
    active: bool,
}

fn main() {
    let u = User { id: 1, email: String::from("a@b.c") };
}
Fig. 4text
error[E0063]: missing field `active` in initializer of `User`
 --> src/bin/e_missingfield.rs:8:13
  |
8 |     let u = User { id: 1, email: String::from("a@b.c") };
  |             ^^^^ missing `active`

There's no undefined. A struct value always has every field filled in. Optional fields are written explicitly with Option<T>, which we'll see shortly, so "this might be missing" is part of the type rather than a surprise.

Methods with impl

Functions that belong to a type go in an impl block:

Fig. 5rust
impl User {
    fn new(id: u64, email: &str, name: &str) -> Self {
        Self {
            id,
            email: email.to_string(),
            name: name.to_string(),
            active: true,
        }
    }

    fn display_name(&self) -> &str {
        if self.name.is_empty() { &self.email } else { &self.name }
    }

    fn deactivate(&mut self) {
        self.active = false;
    }
}

Three kinds of function live here, and the first parameter tells you which:

  1. new has no self parameter. It's an associated function, called with User::new(...), like a static method in TypeScript. Rust has no constructors, and new is just a naming convention for "the usual way to build one". Self inside an impl block means the type being implemented, here User.
  2. display_name(&self) borrows the user immutably. It can read fields but not change them. It's called with user.display_name().
  3. deactivate(&mut self) borrows the user mutably and can change fields.

There's also a fourth form, fn consume(self), which takes ownership and uses the value up. You'll see it on builders and on conversions like into_string().

These are exactly the ownership rules from part 3, applied to methods. &self is a shared borrow, &mut self is a mutable borrow, self is a move. If a method tries to change a field through &self, the error is the same one you saw for plain references:

Fig. 6text
error[E0594]: cannot assign to `self.hits`, which is behind a `&` reference
 --> src/bin/e_selfmut.rs:7:9
  |
7 |         self.hits += 1;
  |         ^^^^^^^^^^^^^^ `self` is a `&` reference, so it cannot be written to
  |
help: consider changing this to be a mutable reference
  |
6 |     fn hit(&mut self) {
  |             +++

The field shorthand in new works like JavaScript's: id alone means id: id.

Using it:

Fig. 7rust
let mut ana = User::new(1, "ana@example.com", "Ana");
println!("{} <{}> active={}", ana.display_name(), ana.email, ana.active);

ana.deactivate();
println!("after deactivate: active={}", ana.active);
Fig. 8text
Ana <ana@example.com> active=true
after deactivate: active=false

Note the let mut ana. Calling a &mut self method needs a mutable variable, because it changes the value. In Rust, mutability belongs to the binding, not the type. There's no separate "readonly User" type. A User in a let binding is read-only, and the same User in a let mut binding isn't.

Struct update syntax

Fig. 9rust
let bo = User {
    id: 2,
    email: String::from("bo@example.com"),
    ..ana.clone()
};

..ana.clone() fills the remaining fields from another value, like { ...ana, id: 2, email: "..." } in JavaScript. The spread goes last in Rust, and fields written explicitly take priority. I cloned ana because the spread moves the fields it uses, and name is a String, so without the clone ana would be partly moved and unusable. That's part 3 showing up again.

Derive: free behaviour

Now the #[derive(Debug, Clone, PartialEq)] line. Rust types don't come with any behaviour by default. You can't print them for debugging, compare them or copy them until you say so. derive asks the compiler to generate the standard implementation.

Try printing a struct without Debug:

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

With it, {:?} prints the struct on one line, and {:#?} pretty-prints it:

Fig. 11text
User { id: 2, email: "bo@example.com", name: "Ana", active: false }
User {
    id: 2,
    email: "bo@example.com",
    name: "Ana",
    active: false,
}
same? false

The derives you'll use constantly:

Derive What it gives you TypeScript equivalent
Debug {:?} printing console.log(obj)
Clone .clone() deep copy structuredClone(obj)
Copy Implicit copy on assignment (only for small all-Copy types) Primitive behaviour
PartialEq == comparing every field A deep equality helper
Default User::default() with zeroes and empty strings An object of defaults
Hash, Eq Use as a HashMap key or in a HashSet Map keys

That same? false line came from ana == bo, which only works because of PartialEq. In JavaScript, == on two objects compares identity, so two objects with the same contents are never equal. In Rust, derived == compares contents, field by field. When we get to Axum, two more derives from the serde crate, Serialize and Deserialize, will turn structs into JSON and back.

Tuple structs and newtypes

Structs can have unnamed fields:

Fig. 12rustRun
struct Point(i32, i32);
struct Meters(f64);

let p = Point(3, 4);
let Point(x, y) = p;
let height = Meters(1.8);
println!("point ({x}, {y}), height {} m", height.0);
Fig. 13text
point (3, 4), height 1.8 m

A one-field tuple struct is called a newtype, and it's one of the most useful patterns in Rust for web code. struct UserId(u64); and struct OrderId(u64); are both just a u64 in memory, with zero runtime cost, but the compiler won't let you pass an OrderId to a function expecting a UserId. If you've ever had a bug from swapping two ID arguments in a JavaScript function, this is the fix.

Enums

More than named constants

Here's a payment status, the kind of thing every e-commerce backend has:

Fig. 14rust
#[derive(Debug)]
enum PaymentStatus {
    Pending,
    Paid { amount_cents: u64, receipt: String },
    Refunded { amount_cents: u64 },
    Failed(String),
}

Four variants, and each one carries different data. Pending carries nothing. Paid carries an amount and a receipt number. Refunded carries only an amount. Failed carries a reason string. A value of type PaymentStatus is exactly one of those four, with exactly that variant's data.

The TypeScript version is a discriminated union:

Fig. 15ts
type PaymentStatus =
  | { kind: "pending" }
  | { kind: "paid"; amountCents: number; receipt: string }
  | { kind: "refunded"; amountCents: number }
  | { kind: "failed"; reason: string };

If you've written those, you already understand Rust enums. The Rust version is shorter because the tag, kind, is built in, and stricter in ways we'll see in a moment.

Compare that with the way this is often modelled without unions:

Fig. 16ts
interface Payment {
  status: "pending" | "paid" | "refunded" | "failed";
  amountCents?: number;
  receipt?: string;
  failureReason?: string;
}

That type allows a "pending" payment with a receipt, a "paid" payment with no amount, and a "failed" payment with no reason. Nothing stops you from creating those, and every function reading a Payment has to defend against them. With the enum, those states can't be constructed at all. A Paid without a receipt is a compile error. That's what "make invalid states unrepresentable" means, and it's the most valuable modelling habit you can take from Rust, whichever language you're writing.

Matching on an enum

You get data out of an enum with match:

Fig. 17rust
impl PaymentStatus {
    fn label(&self) -> String {
        match self {
            PaymentStatus::Pending => "waiting for payment".to_string(),
            PaymentStatus::Paid { amount_cents, receipt } => {
                format!("paid ${}.{:02} (receipt {receipt})", amount_cents / 100, amount_cents % 100)
            }
            PaymentStatus::Refunded { amount_cents } => {
                format!("refunded ${}.{:02}", amount_cents / 100, amount_cents % 100)
            }
            PaymentStatus::Failed(reason) => format!("failed: {reason}"),
        }
    }

    fn is_settled(&self) -> bool {
        matches!(self, PaymentStatus::Paid { .. } | PaymentStatus::Refunded { .. })
    }
}

Each arm is a pattern. PaymentStatus::Paid { amount_cents, receipt } both checks which variant it is and pulls the fields out into variables, in one step. In TypeScript you'd check p.kind === "paid" and then rely on narrowing to access p.receipt. Here the variable receipt only exists inside the arm where it's guaranteed to be there.

matches! is a shorthand for "does this match the pattern, true or false". { .. } means "ignore the fields".

The money is stored as integer cents, as recommended in part 2, and formatted with {:02} to pad the cents to two digits.

Fig. 18rust
let payments = vec![
    PaymentStatus::Pending,
    PaymentStatus::Paid { amount_cents: 1999, receipt: String::from("R-1001") },
    PaymentStatus::Refunded { amount_cents: 500 },
    PaymentStatus::Failed(String::from("card declined")),
];
for p in &payments {
    println!("{:<32} settled={}", p.label(), p.is_settled());
}
Fig. 19text
waiting for payment              settled=false
paid $19.99 (receipt R-1001)     settled=true
refunded $5.00                   settled=true
failed: card declined            settled=false
Paid { amount_cents: 1999, receipt: "R-1001" }

Exhaustiveness

Here's what makes this better than the TypeScript version in practice. Add a variant and forget to handle it:

Fig. 20rust
enum Status {
    Active,
    Suspended,
    Deleted,
}

fn label(s: &Status) -> &'static str {
    match s {
        Status::Active => "active",
        Status::Suspended => "suspended",
    }
}
Fig. 21text
error[E0004]: non-exhaustive patterns: `&Status::Deleted` not covered
  --> src/bin/e_nonexhaustive.rs:8:11
   |
 8 |     match s {
   |           ^ pattern `&Status::Deleted` not covered
   |
note: `Status` defined here
  --> src/bin/e_nonexhaustive.rs:1:6
   |
 1 | enum Status {
   |      ^^^^^^
...
 4 |     Deleted,
   |     ------- not covered
   = note: the matched value is of type `&Status`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
   |
10 ~         Status::Suspended => "suspended",
11 ~         &Status::Deleted => todo!(),
   |

The program doesn't compile until every match on Status handles Deleted. Think about what that means on a real codebase. You add a new order state, PartiallyShipped, and the compiler gives you a list of every place in the code that needs to decide what to do with it. In TypeScript you can get something similar with a never check in a switch default, but it's opt-in, you have to remember it in every switch, and it doesn't apply to if chains. In Rust, every match is checked, always.

This applies to anything you match on, not only enums. Here's a match on an HTTP status code that misses ranges:

Fig. 22text
error[E0004]: non-exhaustive patterns: `0_u16..=199_u16`, `201_u16..=399_u16` and `500_u16..=u16::MAX` not covered
 --> src/bin/e_intmatch.rs:3:22
  |
3 |     let text = match code {
  |                      ^^^^ patterns `0_u16..=199_u16`, `201_u16..=399_u16` and `500_u16..=u16::MAX` not covered

The compiler worked out precisely which numbers were left uncovered.

A word of caution about _. A wildcard arm satisfies exhaustiveness, which is convenient, but it also means new variants silently fall into it. On enums you control, I prefer listing every variant explicitly so the compiler can warn me when one is added.

Enums with methods: a shape example

Enums can have impl blocks just like structs, and this is where they start replacing class hierarchies:

Fig. 23rust
#[derive(Debug)]
enum Shape {
    Circle { radius: f64 },
    Rect { width: f64, height: f64 },
    Triangle { base: f64, height: f64 },
}

impl Shape {
    fn area(&self) -> f64 {
        match self {
            Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
            Shape::Rect { width, height } => width * height,
            Shape::Triangle { base, height } => 0.5 * base * height,
        }
    }
}
Fig. 24text
Circle { radius: 1.0 } has area 3.14
Rect { width: 3.0, height: 4.0 } has area 12.00
Triangle { base: 6.0, height: 2.0 } has area 6.00
total area 21.14

In an object-oriented language you'd write an abstract Shape class with Circle, Rect and Triangle subclasses, each overriding area(). The enum version keeps all the area logic in one place, and adding a new shape makes the compiler point at every function that needs updating. Neither approach is better everywhere. If the set of variants is fixed and you keep adding operations, enums fit better. If other people need to add new kinds without touching your code, traits fit better, and that's part 7.

Option: the enum you already met

You've already been using an enum since part 2. Option is defined in the standard library as:

Fig. 25rust
enum Option<T> {
    None,
    Some(T),
}

That's it. No special language feature. checked_add returned None, .chars().next() returned Some('c'). Rust has no null. A value that might be absent is an Option, and you can't use the inside value without first checking which variant it is. Tony Hoare, who invented null references, has called them his "billion-dollar mistake". Rust's answer is to make absence a regular enum that the type checker can see.

Result<T, E>, with variants Ok(T) and Err(E), is the same idea for operations that can fail. Both get a full part next time.

Pattern matching in depth

Patterns are more powerful than switch cases, and they show up in more places than match. Here's a small request router, the sort of thing every web framework does internally, written as one match:

Fig. 26rust
#[derive(Debug)]
enum Method {
    Get,
    Post,
    Delete,
}

struct Request<'a> {
    method: Method,
    path: &'a str,
    user_id: Option<u64>,
}

fn route(req: &Request) -> String {
    let parts: Vec<&str> = req.path.trim_matches('/').split('/').collect();
    match (&req.method, parts.as_slice(), req.user_id) {
        (Method::Get, [""], _) => "home page".to_string(),
        (Method::Get, ["posts"], _) => "list posts".to_string(),
        (Method::Get, ["posts", id], _) => format!("show post {id}"),
        (Method::Post, ["posts"], Some(uid)) => format!("create post as user {uid}"),
        (Method::Post, ["posts"], None) => "401: log in first".to_string(),
        (Method::Delete, ["posts", id], Some(uid)) if uid == 1 => format!("admin deletes post {id}"),
        (Method::Delete, ["posts", _], _) => "403: admins only".to_string(),
        (m, _, _) => format!("404: no route for {m:?} {}", req.path),
    }
}
Fig. 27text
Get     /          -> home page
Get     /posts     -> list posts
Get     /posts/42  -> show post 42
Post    /posts     -> create post as user 7
Post    /posts     -> 401: log in first
Delete  /posts/42  -> admin deletes post 42
Delete  /posts/42  -> 403: admins only
Get     /admin     -> 404: no route for Get /admin

(Request<'a> has a lifetime parameter because it holds a borrowed &str. That's the "structs that hold references" case from part 3. It means a Request can't outlive the string its path points into.)

There's a lot happening in that match, so let's take it apart:

  1. We match on a tuple of three things at once: the method, the path segments and the optional user ID. Matching on a tuple lets one match make a decision based on several values.
  2. parts.as_slice() lets us use slice patterns. ["posts"] matches a slice with exactly one element equal to "posts". ["posts", id] matches exactly two elements where the first is "posts", and binds the second to id.
  3. Some(uid) matches only when a user is logged in, and binds their ID. None matches when nobody is.
  4. _ ignores a position.
  5. if uid == 1 is a match guard: an extra condition the arm needs before it matches. If the guard fails, matching continues with the next arm.
  6. Arms are tried top to bottom, and the first match wins. That's why the specific admin arm comes before the general ["posts", _] arm.
  7. The final (m, _, _) catches everything else and binds the method so we can print it.

Axum's router does something more efficient than this, but the logic is the same, and you'll see path extraction like ["posts", id] again in part 10 as Path(id).

Ranges, guards and bindings

Fig. 28rust
let age = 34;
let bracket = match age {
    0 => "newborn",
    1..=12 => "child",
    13..=19 => "teen",
    n if n >= 65 => "senior",
    _ => "adult",
};
Fig. 29text
34 is adult

n if n >= 65 binds the value to n and then checks a guard. You can also bind and test a range together with @:

Fig. 30rust
let msg = match n {
    x @ 10..=20 => format!("{x} is between 10 and 20"),
    x => format!("{x} is outside"),
};
Fig. 31text
15 is between 10 and 20

if let: when you only care about one case

A full match is a lot of ceremony when you only want one variant:

Fig. 32rustRun
let maybe_id: Option<u64> = Some(7);
if let Some(id) = maybe_id {
    println!("if let found user {id}");
}
Fig. 33text
if let found user 7

if let PATTERN = VALUE runs the block only if the pattern matches, with the bindings available inside. It can have an else. Think of it as an if that also destructures.

let-else: unwrap or leave

The opposite situation is common in request handlers: you need a value to continue, and if it isn't there, you want to bail out early.

Fig. 34rust
let Some(id) = maybe_id else {
    println!("no user");
    return;
};
println!("let-else continues with user {id}");
Fig. 35text
let-else continues with user 7

If the pattern matches, id is available for the rest of the function. If it doesn't, the else block runs, and it must leave: return, break, continue, or a panic. This keeps the happy path unindented, the same idea as guard clauses in JavaScript (if (!user) return;), but the compiler guarantees that id exists afterwards.

Patterns everywhere

Patterns aren't only for match. You've been using them all along:

  • let (x, y, name) = point; destructures a tuple.
  • let Point(x, y) = p; destructures a tuple struct.
  • for (index, lang) in langs.iter().enumerate() destructures each item.
  • Function parameters can be patterns too: fn print_point(&(x, y): &(i32, i32)).

Once you know the pattern syntax, it works the same in every one of those places.

TypeScript and Rust, side by side

TypeScript Rust
interface User { ... } struct User { ... }
class User { constructor() {} } struct User plus impl User { fn new() -> Self }
static create() Associated function fn create() -> Self
Method that reads this fn name(&self)
Method that changes this fn name(&mut self)
{ ...a, id: 2 } User { id: 2, ..a }
name?: string name: Option<String>
type Id = number (alias, interchangeable) struct Id(u64) (distinct type)
enum Color { Red, Green } enum Color { Red, Green }
Discriminated union with kind enum with data in each variant
switch (x.kind) match x (exhaustive)
never check in default Built in, always on
if (x.kind === "paid") { x.receipt } if let Paid { receipt, .. } = x { receipt }
if (!user) return; let Some(user) = user else { return };
null / undefined Option::None
console.log(obj) println!("{obj:?}") with #[derive(Debug)]
a === b on objects (identity) a == b with PartialEq (contents)

Back to wordfreq

Our word counter's argument handling has grown messy. In part 2 we checked args[2] == "--top" by position, which means --top has to come straight after the file name, and adding any other option would make it worse. Let's use this part's tools: a struct for the configuration, an enum for the sort order, and pattern matching to parse arguments in any order.

The new types:

Fig. 36rust
#[derive(Debug, Clone, Copy, PartialEq)]
enum SortBy {
    Count,
    Alpha,
    Length,
}

#[derive(Debug, PartialEq)]
struct Config {
    path: String,
    top: usize,
    sort: SortBy,
}

SortBy can derive Copy because it carries no data. It's as cheap to copy as a number. Config can't, because it holds a String.

The parser lives on Config as an associated function:

Fig. 37rust
impl Config {
    fn from_args(args: &[String]) -> Result<Config, String> {
        let [_, path, rest @ ..] = args else {
            return Err("usage: wordfreq <file> [--top N] [--sort count|alpha|length]".to_string());
        };

        let mut config = Config {
            path: path.clone(),
            top: 5,
            sort: SortBy::Count,
        };

        let mut i = 0;
        while i < rest.len() {
            match (rest[i].as_str(), rest.get(i + 1)) {
                ("--top", Some(value)) => {
                    config.top = match value.parse::<usize>() {
                        Ok(n) if n > 0 => n,
                        _ => {
                            return Err(format!(
                                "--top needs a whole number above 0, got {value:?}"
                            ));
                        }
                    };
                }
                ("--sort", Some(value)) => {
                    config.sort = match value.as_str() {
                        "count" => SortBy::Count,
                        "alpha" => SortBy::Alpha,
                        "length" => SortBy::Length,
                        other => {
                            return Err(format!(
                                "unknown sort {other:?}, use count, alpha or length"
                            ));
                        }
                    };
                }
                (flag @ ("--top" | "--sort"), None) => return Err(format!("{flag} needs a value")),
                (other, _) => return Err(format!("unknown option {other:?}")),
            }
            i += 2;
        }

        Ok(config)
    }
}

Almost everything from this part is in there:

  • let [_, path, rest @ ..] = args else { ... } is a slice pattern with let-else. It needs at least two arguments: the program name, which we ignore, and the path. rest @ .. binds everything after them as a slice. If there are fewer than two, we return the usage message.
  • We match on a tuple of the current flag and the next value. rest.get(i + 1) returns an Option, so Some(value) matches when a value follows the flag and None when the flag was the last argument.
  • flag @ ("--top" | "--sort") binds whichever flag it was, so one arm produces both "needs a value" messages.
  • The function returns Result<Config, String>: either a valid config or an error message. main decides what to do with an error. That split, parse functions return errors and main prints them, makes from_args easy to test, as you'll see below. Part 5 is all about Result.

main now starts with:

Fig. 38rust
let config = match Config::from_args(&args) {
    Ok(config) => config,
    Err(message) => {
        eprintln!("{message}");
        process::exit(1);
    }
};

And top_words takes the sort order and matches on it:

Fig. 39rust
fn top_words(counts: &HashMap<String, usize>, n: usize, sort: SortBy) -> Vec<(&str, usize)> {
    let mut pairs: Vec<(&str, usize)> = counts
        .iter()
        .map(|(word, count)| (word.as_str(), *count))
        .collect();
    match sort {
        SortBy::Count => pairs.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))),
        SortBy::Alpha => pairs.sort_by(|a, b| a.0.cmp(b.0)),
        SortBy::Length => pairs.sort_by(|a, b| {
            b.0.chars()
                .count()
                .cmp(&a.0.chars().count())
                .then(a.0.cmp(b.0))
        }),
    }
    pairs.truncate(n);
    pairs
}

If you ever add a fourth sort order to SortBy, this match stops compiling until you handle it. That's the exhaustiveness check working for you.

Flags now work in any order:

Fig. 40bash
cargo run -q -- notes.txt --sort length --top 3
Fig. 41text
3 lines, 27 words, 16 unique
longest word: compiler (8 chars)
9.0 words per line
sorted by Length

 1. compiler     2 ##
 2. fetches      1 #
 3. helpful      1 #
Fig. 42bash
cargo run -q -- notes.txt --top 4 --sort alpha
Fig. 43text
sorted by Alpha

 1. and          2 ##
 2. builds       1 #
 3. cargo        3 ###
 4. code         1 #

And every kind of bad input gets a specific message, each exiting with status 1:

Fig. 44text
unknown sort "random", use count, alpha or length
--top needs a value
unknown option "--colour"
usage: wordfreq <file> [--top N] [--sort count|alpha|length]

Testing the parser

Because from_args takes a slice of strings and returns a Result, testing it needs no files and no process. A small helper builds the argument list:

Fig. 45rustRun
fn args(list: &[&str]) -> Vec<String> {
    list.iter().map(|s| s.to_string()).collect()
}

#[test]
fn config_defaults() {
    let config = Config::from_args(&args(&["wordfreq", "notes.txt"])).unwrap();
    assert_eq!(
        config,
        Config { path: "notes.txt".to_string(), top: 5, sort: SortBy::Count }
    );
}

#[test]
fn config_reads_flags_in_any_order() {
    let config =
        Config::from_args(&args(&["wordfreq", "a.txt", "--sort", "alpha", "--top", "3"]))
            .unwrap();
    assert_eq!(config.top, 3);
    assert_eq!(config.sort, SortBy::Alpha);
}

#[test]
fn config_rejects_bad_sort() {
    let err = Config::from_args(&args(&["wordfreq", "a.txt", "--sort", "random"])).unwrap_err();
    assert!(err.contains("unknown sort"));
}

assert_eq!(config, Config { ... }) compares whole structs, which works because of #[derive(PartialEq)]. And if it fails, the test output prints both values, which works because of #[derive(Debug)]. This is why nearly every struct in a Rust codebase derives both.

Fig. 46text
.......
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Clippy is clean and cargo fmt made no complaints. In real projects you'd use the clap crate for argument parsing rather than writing your own, and part 6 introduces it. But writing a parser by hand once is a great way to practise patterns.

Exercises

  1. Add a --reverse flag that takes no value. Where does the i += 2 logic break, and how would you restructure the loop to handle flags with and without values?
  2. Write an enum OrderStatus for an online shop with at least four states, where a shipped order carries a tracking number and a cancelled order carries a reason. Write fn can_cancel(&self) -> bool with matches!.
  3. Add struct Email(String) with a fn parse(s: &str) -> Option<Email> that returns None if there's no @. Change User to use it. What does that buy you elsewhere in the code?
  4. Extend the router with PUT /posts/:id, which requires a logged-in user. Then add a Put variant to Method and see which matches the compiler makes you fix.
  5. Rewrite Shape::area without the match, using if let for each variant. Compare the two. Which one tells you when you forget a shape?

Next up: error handling

You've now seen Option and Result used a dozen times, mostly through match and the occasional .unwrap(). In part 5 we give them a proper look. Rust has no exceptions and no try/catch. Errors are ordinary values, returned like any other, and the ? operator makes passing them up the call stack as short as it is in languages with exceptions. We'll write custom error types with enums, which you can now read, see when panicking is the right call, and remove every process::exit from the middle of wordfreq's main function.