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.
Code
#[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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Enum Variants Carrying Data?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.