OSRust.010: Rust Enums and Pattern Matching — Variants, Payloads and Exhaustive State Handling

Conceptual illustration of three rack-monitoring devices representing distinct enum states.

Open-Source Rust Programming • Intermediate • Estimated study time: 45 minutes.

An enum represents a value that belongs to one of several named alternatives. Each alternative, called a variant, may carry a different payload. The preceding Rust structs and methods lesson grouped fields into records; enums express mutually exclusive states. Combining both techniques helps encode application constraints in the type system rather than relying entirely on runtime conventions.

Prerequisites and learning objectives

Install Rust using rustup and review ownership and borrowing, borrowed text and slices and Result and Option. By completion, learners can declare payload-bearing variants, destructure variants with match, apply guards, borrow rather than move payloads, and recognize the compiler’s exhaustiveness requirement. Use only synthetic monitoring data in the laboratory.

Variants and payloads

The official Rust Book chapter on enums introduces enumeration types. An enum value has exactly one active variant. A unit-like variant has no payload, a tuple-like variant contains positional fields, and a struct-like variant contains named fields. For a rack monitor, Offline carries no reading, Online carries a temperature and Fault carries a diagnostic message. The type prevents construction of an Offline value containing an Online payload. An integer temperature of zero remains a valid measurement rather than a special absence marker.

RustCurious 6: Enums and Polymorphism covers enum alternatives and pattern matching, including if let and nested matches. Watch at source.

Exhaustive matches and guards

A match expression compares a value against patterns in order and evaluates the first eligible arm. The Rust Book match chapter explains the compiler’s coverage requirement. Every possible input must be covered. A guard adds a Boolean condition after a pattern; if it fails, evaluation continues to later arms. A guarded Online arm alone does not cover all Online values. A second unguarded Online arm handles the remaining readings. All arms must produce compatible result types. A wildcard can deliberately accept remaining cases, but explicit variants are often more maintainable for closed application states.

Learn Rust: Enums, Option, and Pattern Matching introduces enum values and the match construct. Watch at source.

Borrowing payloads

Matching against a shared reference can bind references to the contained data through Rust’s match ergonomics. The diagnostic String remains owned by the RackState value in the laboratory because label accepts &RackState. The integer payload is accessed through a borrowed binding and copied when necessary. A match on an owned value can instead move non-Copy payloads, so choose the scrutinee according to ownership requirements. The pattern syntax chapter explains destructuring and guards. The if let construct offers a concise conditional match when only one variant matters; it does not itself require explicit coverage of every alternative.

Laboratory: a typed rack-monitoring state

The sample models three states, classifies synthetic temperatures at a threshold of 35 degrees Celsius, and exposes a reading only for an Online variant. The threshold is an arbitrary instructional value, not a recommended operating limit. Save the following complete program as main.rs:

enum RackState {
    Offline,
    Online { temp_c: i32 },
    Fault(String),
}
 
fn label(state: &RackState) -> String {
    match state {
        RackState::Offline => "offline".to_owned(),
        RackState::Online { temp_c } if *temp_c >= 35 => {
            format!("hot: {temp_c} C")
        }
        RackState::Online { temp_c } => {
            format!("normal: {temp_c} C")
        }
        RackState::Fault(message) => {
            format!("fault: {message}")
        }
    }
}
 
fn temperature(state: &RackState) -> Option<i32> {
    if let RackState::Online { temp_c } = state {
        Some(*temp_c)
    } else {
        None
    }
}
 
fn main() {
    let state = RackState::Online { temp_c: 24 };
    println!("{}", label(&state));
}
 
#[cfg(test)]
mod tests {
    use super::*;
 
    #[test]
    fn offline() {
        assert_eq!(label(&RackState::Offline), "offline");
        assert_eq!(temperature(&RackState::Offline), None);
    }
 
    #[test]
    fn zero_is_valid() {
        let state = RackState::Online { temp_c: 0 };
        assert_eq!(temperature(&state), Some(0));
        assert_eq!(label(&state), "normal: 0 C");
    }
 
    #[test]
    fn threshold() {
        assert_eq!(label(&RackState::Online { temp_c: 34 }),
                   "normal: 34 C");
        assert_eq!(label(&RackState::Online { temp_c: 35 }),
                   "hot: 35 C");
    }
 
    #[test]
    fn borrowed_fault() {
        let state = RackState::Fault("sensor unavailable".into());
        assert_eq!(label(&state), "fault: sensor unavailable");
        assert_eq!(temperature(&state), None);
        assert_eq!(label(&state), "fault: sensor unavailable");
    }
}

Compile and execute the program, then build and run the four built-in test functions using the following commands:

rustc --edition=2021 main.rs -o rack_demo
./rack_demo
rustc --edition=2021 --test main.rs -o rack_tests
./rack_tests

Expected results: the executable prints normal: 24 C. All four test functions should pass, checking offline state, a legitimate zero reading, the threshold boundary, and repeated access to a borrowed fault payload. The editorial environment did not provide rustc or Cargo, so the example and tests were reviewed against documented language rules but were not compiled or executed. Actual results must be confirmed in a local Rust toolchain.

Deliberately incomplete match

Save the following intentionally invalid example as incomplete.rs:

enum State { Offline, Online }
 
fn label(state: State) -> &'static str {
    match state {
        State::Offline => "offline",
    }
}
 
fn main() {
    println!("{}", label(State::Offline));
}

Compile the isolated example with the following command:

rustc --edition=2021 incomplete.rs

Expected outcome: the compiler rejects the missing Online arm with a non-exhaustive pattern diagnostic (E0004). Add an explicit Online arm returning an appropriate string to repair the example. Compiler rejection has not been executed in the editorial environment.

Engineering limitations

The enum represents a single state, not a complete device lifecycle. A production monitor must define authorized transitions, timestamps, calibrated sensor limits and concurrency rules. A shared reference prevents ordinary direct mutation of the payload during the call, but does not make every possible type thread-safe. Explicitly matching variants improves coverage when the enum evolves; wildcard arms may conceal a newly added state. Use a meaningful application policy rather than assigning fabricated values to missing readings.

Exercises and answer key

Exercise 1: Add a Maintenance variant and explain which match must change. Exercise 2: Predict the label for 35 C. Exercise 3: Explain why temperature returns Some(0) for an online zero reading. Exercise 4: Explain why label can inspect the same Fault value twice. Exercise 5: Describe the role of the unguarded Online arm.

Answers: 1. The exhaustive match in label needs an additional arm; temperature already has an else branch. 2. hot: 35 C because the guard includes equality. 3. The variant establishes presence independently of the numeric value. 4. The function borrows the enum and does not move the String. 5. It covers online readings that fail the guard.

Conclusion

Enums represent mutually exclusive alternatives and carry state-specific data. Exhaustive matches translate those alternatives into explicit behavior, guards refine decisions, and borrowed patterns preserve ownership. Verify both valid behavior and intended compile-time failures before relying on the model in operational software.

Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

BitcoinVersus.Tech donation QR code for 5,000 satoshis

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.

BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

Leave a Reply