Rust for Pythonistas

Lesson 10 of 26

Enums and match

A Python Enum is a set of names. A Rust enum is also a set of names, but each name (each variant) can carry data of its own. One Rust enum can therefore replace a small group of related classes.

To read an enum you need match. It is Python's if/elif chain or the newer match/case, with one extra rule: the compiler checks that you handled every variant. Miss one and the program does not build. That check is the main reason Rust code has so many match blocks.

A Python Enum and a Rust enum

The simplest kind: variants with no data at all. Names inside an enum are written in UpperCamelCase in Rust, not UPPER_CASE.

Python
from enum import Enum

class Status(Enum):
    OPEN = "open"
    CLOSED = "closed"

status = Status.OPEN
if status is Status.OPEN:
    print("The ticket is open")
else:
    print("The ticket is closed")
Rust
enum Status {
    Open,
    Closed,
}

fn main() {
    let status = Status::Open;
    match status {
        Status::Open => println!("The ticket is open"),
        Status::Closed => println!("The ticket is closed"),
    }
}
Output
The ticket is open

Variants can carry data

This is the big difference from a Python Enum. Circle(f64) carries one number, like a dataclass with one field. Rect { w: f64, h: f64 } carries named fields, like a dataclass with two. One enum holds both, and a Vec of that enum holds a mix of them.

In Python you would write two classes and ask isinstance. In Rust you match and the pattern pulls the data out.

Python
from dataclasses import dataclass

@dataclass
class Circle:
    radius: float

@dataclass
class Rect:
    w: float
    h: float

def area(shape):
    if isinstance(shape, Circle):
        return 3.14159 * shape.radius ** 2
    return shape.w * shape.h

for s in [Circle(1.0), Rect(3.0, 4.0)]:
    print(f"{area(s):.2f}")
Rust
enum Shape {
    Circle(f64),
    Rect { w: f64, h: f64 },
}

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

fn main() {
    let shapes = vec![Shape::Circle(1.0), Shape::Rect { w: 3.0, h: 4.0 }];
    for s in &shapes {
        println!("{:.2}", area(s));
    }
}
Output
3.14
12.00

match is an expression: guards, | and ranges

Python 3.10 added match/case, and Rust's match reads almost the same. Two differences to notice. First, a Rust match returns a value, so it can sit on the right of a let; the Python side has to return from a function instead. Second, the compiler checks that the arms cover everything.

Python
def describe(n):
    match n:
        case 0:
            return "zero"
        case 1 | 2:
            return "one or two"
        case 3 | 4 | 5 | 6 | 7 | 8 | 9:
            return "three to nine"
        case n if n < 0:
            return "negative"
        case _:
            return "large"

for n in [0, 2, 5, -5, 42]:
    print(f"{n}: {describe(n)}")
Rust
fn main() {
    for n in [0, 2, 5, -5, 42] {
        let label = match n {
            0 => "zero",
            1 | 2 => "one or two",
            3..=9 => "three to nine",
            n if n < 0 => "negative",
            _ => "large",
        };
        println!("{n}: {label}");
    }
}
Output
0: zero
2: one or two
5: three to nine
-5: negative
42: large

Miss one variant and it does not compile

In Python, forgetting a case is silent: a yellow light would simply print nothing. Rust counts the variants and refuses to build the program. The error E0004 is one you will meet often; the fix is a missing arm, or _ if any other value is fine.

Python
from enum import Enum

class TrafficLight(Enum):
    RED = "red"
    YELLOW = "yellow"
    GREEN = "green"

light = TrafficLight.GREEN
if light is TrafficLight.RED:
    print("stop")
elif light is TrafficLight.GREEN:
    print("go")
Rust
enum TrafficLight {
    Red,
    Yellow,
    Green,
}

fn main() {
    let light = TrafficLight::Green;
    match light {
        TrafficLight::Red => println!("stop"),
        TrafficLight::Green => println!("go"),
    }
}
Output
go

Methods on an enum

An enum can have an impl block, just like a struct (lesson 9). The method usually matches on self and turns the variant into a number or a string. This is the closest thing to a Python Enum whose members have a value.

Python
from enum import Enum

class Coin(Enum):
    PENNY = 1
    NICKEL = 5
    DIME = 10
    QUARTER = 25

    @property
    def cents(self):
        return self.value

coins = [Coin.PENNY, Coin.QUARTER, Coin.QUARTER]
print(sum(c.cents for c in coins))
Rust
enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

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

fn main() {
    let coins = vec![Coin::Penny, Coin::Quarter, Coin::Quarter];
    let total: u32 = coins.iter().map(|c| c.cents()).sum();
    println!("{total}");
}
Output
51

Where the Python analogy breaks

Cheat card

PythonRust
class Status(Enum): OPEN = "open"enum Status { Open, }
Status.OPENStatus::Open
Status.OPEN.name # "OPEN"match status { Status::Open => "Open", ... }
match x: case 1:match x { 1 => ...
case 0:0 => ...
case 1 | 2:1 | 2 => ...
case 3 | 4 | 5 | 6 | 7 | 8 | 9:3..=9 => ...
case n if n < 0:n if n < 0 => ...
case _:_ => ...
isinstance(s, Circle)Shape::Circle(r) => ...
result = describe(x)let result = match x { ... };
def cents(self): # in the Enum classimpl Coin { fn cents(&self) -> u32 { ... } }

← Structs and impl Option instead of None →