Enum Variants Carrying Data

Model message types as enum variants with payloads and consume them with match, so invalid states cannot be constructed at all.

RustData Integrity

Code

rustsnippet
25 lines
#[derive(Debug)]
enum Signal {
    Ping,
    Text { author: String, body: String },
    Quit { code: i32 },
}

fn render(signal: &Signal) -> String {
    match signal {
        Signal::Ping => String::from("heartbeat"),
        Signal::Text { author, body } => format!("@{}: {}", author, body),
        Signal::Quit { code } => format!("exit {}", code),
    }
}

fn main() {
    let inbox = [
        Signal::Ping,
        Signal::Text { author: "alice".into(), body: "deploy ready".into() },
        Signal::Quit { code: 0 },
    ];
    for signal in &inbox {
        println!("{}", render(signal));
    }
}

How it works

Count the functions render and main as the entire surface area of Enum Variants Carrying Data.

Repetition is confined to for signal in &inbox — the rest of the file is straight-line. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Applying it

The main signature reads fn render(signal: &Signal) -> String

There are 1 call inside main — render — executed top to bottom.

Statements that matter

fn render(signal: &Signal) -> String {
match signal {
Signal::Ping => String::from("heartbeat"),
Signal::Text { author, body } => format!("@{}: {}", author, body),
Signal::Quit { code } => format!("exit {}", code),
}
}

Interactive Tools for This Topic

FAQ

How do you run Enum Variants Carrying Data?
Nothing to install first — run the file and the program does the rest.