---
title: "Structs, enums and match in Rust"
slug: "structs-enums-and-match"
description: "Define structs with methods in an impl block, enums that carry data, and use match and if let to handle every case, including Option. Fix a missing arm."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-rust/structs-enums-and-match"
---

# Structs, enums and match in Rust

How do you model your own data in Rust?

## Predict

```rust
enum Light {
    Red,
    Yellow,
    Green,
}

fn main() {
    for light in [Light::Red, Light::Yellow, Light::Green] {
        match light {
            Light::Red => println!("stop"),
            Light::Green => println!("go"),
            _ => println!("wait"),
        }
    }
}
```

What does this program print?

- stop, then go, then wait
- stop, then stop, then go
- stop, then wait, then go

Answer: stop, then wait, then go — Red and Green have their own arms, and the _ arm catches Yellow.

Output:

```
stop
wait
go
```

The `_` arm matches every value the earlier arms did not, so Yellow prints wait.

## Structs and methods

A **struct** groups named fields: `struct Rectangle { width: u32, height: u32 }`. You make an instance by giving every field a value and read a field with a dot. Methods live in an `impl` block. A method whose first parameter is `&self` borrows the instance, so you call `rect.area()` and still own `rect` afterwards.

## A struct with a method

```rust
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect = Rectangle {
        width: 30,
        height: 50,
    };
    println!("{:?}", rect);
    println!("area is {}", rect.area());
}
```

Output:

```
Rectangle { width: 30, height: 50 }
area is 1500
```

`#[derive(Debug)]` lets `{:?}` print the struct for debugging. `area(&self)` reads the fields through `self`.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=2fef5274712f45b3bca6b0a59517316d

## Enums, Option and match

An **enum** is a type with a fixed set of variants, and a variant can hold data. Rust has no null. A value that may be missing has the type `Option<T>`: `Some(value)` or `None`. `match` compares a value with patterns, and it is **exhaustive**: you must cover every variant, or use `_` for the rest.

## An enum with data, and an Option

```rust
enum Shape {
    Square(f64),
    Rect { w: f64, h: f64 },
}

fn area(shape: &Shape) -> f64 {
    match shape {
        Shape::Square(side) => side * side,
        Shape::Rect { w, h } => w * h,
    }
}

fn main() {
    println!("{}", area(&Shape::Square(3.0)));
    println!("{}", area(&Shape::Rect { w: 2.0, h: 5.0 }));
    let found: Option<u32> = Some(7);
    if let Some(n) = found {
        println!("found {n}");
    }
}
```

Output:

```
9
10
found 7
```

`Square(f64)` holds one number and `Rect { w, h }` holds two named ones; the `match` pulls them out. `if let Some(n)` handles the `Some` case and ignores `None`.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=5c5c3a1945a7c83e848b0ab8abb757a2

## Fix it

```rust
enum Coin {
    Penny,
    Nickel,
    Dime,
}

fn cents(coin: &Coin) -> u32 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
    }
}

fn main() {
    println!("{}", cents(&Coin::Penny));
    println!("{}", cents(&Coin::Nickel));
    println!("{}", cents(&Coin::Dime));
}
```

This program does not compile. What is the bug?

- The match has no arm for Dime, and match must cover every variant
- cents must take Coin by value, not &Coin
- The enum needs #[derive(Debug)] before it can be matched

Answer: The match has no arm for Dime, and match must cover every variant — Add a Coin::Dime arm, or a _ arm, so every case is handled.

Compiler message:

```
error[E0004]: non-exhaustive patterns: `&Coin::Dime` not covered
```

Fixed:

```rust
enum Coin {
    Penny,
    Nickel,
    Dime,
}

fn cents(coin: &Coin) -> u32 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
    }
}

fn main() {
    println!("{}", cents(&Coin::Penny));
    println!("{}", cents(&Coin::Nickel));
    println!("{}", cents(&Coin::Dime));
}
```

Output:

```
1
5
10
```

## Say it back

In your own words: why must a match cover every case?

Our sentence: So that no value can slip through unhandled: if you add a variant later, the compiler points at every match that forgot it instead of failing at run time.

## Mission (10 min)

Define an enum with three variants, one of them holding a number, and a function that matches on it. Add a struct with an impl block and a method, and print both from main. Then remove one match arm and read the error.

```sh
cargo new shapes
cd shapes
cargo run
```

## Common questions

### How do I define a struct in Rust?

Write the keyword struct, a name and a list of named fields with their types in braces, for example struct Rectangle { width: u32, height: u32 }. To make a value, give every field a value, and read a field with a dot. Methods go in a separate impl block, with &self as the first parameter.

### What is Option in Rust and why is there no null?

Rust has no null value. When a value may be missing, its type is Option<T>, an enum with two variants: Some(value) and None. Because it is a different type from T, the compiler makes you handle the None case before you can use the value, so you cannot forget it by accident.

### Why must a match be exhaustive in Rust?

Every match must cover all possible values of what it matches, or the program does not compile. The compiler even names the missing pattern. This means a forgotten case becomes a compile error rather than a bug at run time. If you only care about some cases, a final _ arm covers all the rest.

## Sources

- https://doc.rust-lang.org/book/ch05-01-defining-structs.html (read 2026-12-03)
- https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html (read 2026-12-03)
- https://doc.rust-lang.org/book/ch06-02-match.html (read 2026-12-03)

Measured with rustc 1.100.1 (play.rust-lang.org, stable, edition 2024) on 2026-12-03.
