Enums in Rust
| Enums with data | |
| Match them | |
| Option is an enum | |
| Result is an enum |
Enums with data
An enum lists a fixed set of choices, and each choice can carry different data. This keeps related shapes in one type instead of loose flags plus extra structs.
Declare variants with struct style braces or tuple style parentheses, then build values with two colons and the variant name.
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
fn main() {
let m = Message::Write(String::from("hi"));
}
Message has three variants with three different shapes. The Write variant owns a String, so each message carries exactly the data its kind needs.
Match them
Match reads an enum value and runs the arm for its variant. Each arm names the variant and binds any data inside, so all handling stays in one place.
The compiler warns when an arm is missing, which keeps new variants from slipping through silently.
enum Coin { Penny, Nickel }
fn value(c: Coin) -> u8 {
match c {
Coin::Penny => 1,
Coin::Nickel => 5,
}
}
The value function turns each coin into cents. Add a third variant later and the compiler points at this match until every arm is complete.
Option is an enum
Option is an enum from the standard library with two variants, Some for a value and None for absence. It replaces null with a value the compiler forces handlers to check.
Build Some with a value inside and use None alone, then match or use helper methods to reach the inner value.
fn main() {
let a: Option<i32> = Some(3);
let b: Option<i32> = None;
if a.is_some() {
println!("yes");
}
}
Here a holds a number and b holds nothing. The is_some check shows one way to ask which variant arrived before touching the value.
Result is an enum
Result is another standard library enum with Ok for success and Err for failure. Functions return it when an operation can fail with a message or an error value.
Callers match both arms, so success values and error values each get clear handling in the open.
fn check(n: i32) -> Result<i32, String> {
if n >= 0 {
Ok(n)
} else {
Err(String::from("negative"))
}
}
The check function accepts zero and positive numbers and rejects the rest. Ok carries the number forward while Err carries a short reason.
Next: Advanced match
Article author: Arthur Isaev