RsRust
IntermediateLesson 8 of 16

Enums, match & Option – Rust

Enums with data, exhaustive pattern matching, and handling “no value”.

Rust enums are much more powerful than in C or Java: each variant can carry its own data (algebraic data types). match takes them apart, and the compiler enforces that all cases are handled.

enum Form {
    Kreis(f64),
    Rechteck { b: f64, h: f64 },
    Punkt,
}

fn flaeche(f: &Form) -> f64 {
    match f {
        Form::Kreis(r) => std::f64::consts::PI * r * r,
        Form::Rechteck { b, h } => b * h,
        Form::Punkt => 0.0,
    }
}

fn main() {
    println!("{:.2}", flaeche(&Form::Kreis(1.0)));                 // 3.14
    println!("{}", flaeche(&Form::Rechteck { b: 2.0, h: 3.0 }));   // 6
}

Rust has no null. Instead there is the enum Option<T> with the variants Some(T) and None. The compiler forces you to handle the “empty” case, which eliminates null-pointer crashes.

fn finde(zahlen: &[i32], ziel: i32) -> Option<usize> {
    zahlen.iter().position(|&x| x == ziel)
}

fn main() {
    match finde(&[4, 8, 15], 8) {
        Some(i) => println!("Index {i}"),      // Index 1
        None => println!("not found"),
    }
    if let Some(i) = finde(&[4, 8, 15], 99) {
        println!("Index {i}");
    } else {
        println!("not there");
    }
    let name: Option<&str> = None;
    println!("{}", name.unwrap_or("anonymous"));   // anonymous
}

Patterns can contain ranges, alternatives, guards (if), and bindings (@). With let ... else (since Rust 1.65) you can bail out early:

fn beschreibe(n: i32) -> &'static str {
    match n {
        i32::MIN..=-1 => "negative",
        0 => "zero",
        x if x % 2 == 0 => "positive even",
        1 | 3 | 5 | 7 | 9 => "small odd",
        _ => "large odd",
    }
}

fn erstes_zeichen(s: &str) -> char {
    let Some(c) = s.chars().next() else {
        return '?';
    };
    c
}

fn main() {
    println!("{} {} {}", beschreibe(-3), beschreibe(4), beschreibe(11));
    println!("{} {}", erstes_zeichen("Rust"), erstes_zeichen(""));   // R ?
}
TipUseful Option methods: map, and_then, unwrap_or, unwrap_or_else, unwrap_or_default, ok_or (turns an Option into a Result), is_some, filter, take.
Warningunwrap() and expect() trigger a panic on None. Fine for prototypes and tests, but in production code prefer match, if let, or ?.