Enums and the match expression
A struct says "this data has these fields, all at once". An enum says "this value is one of these possible variants". For example, a traffic light is red, yellow or green, never two at the same time. Rust enums are much more powerful than those of C or Java, because each variant can carry different data. Together with match, which forces you to handle all cases, they form one of the best tools of the language for writing correct programs.
Defining an enum
It is defined with enum and each variant is accessed with ::, like Direction::North. Variants can be simple, carry values like a tuple or carry named fields like a struct. All of them belong to the same type, so you can store them in the same array or pass them to the same function. You can also add methods with impl, just like with a struct.
#[derive(Debug)]
enum Shape {
Circle(f64), // radius
Rectangle { width: f64, height: f64 },
Point, // no data
}
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Circle(r) => 3.14159 * r * r,
Shape::Rectangle { width, height } => width * height,
Shape::Point => 0.0,
}
}
}
fn main() {
let shapes = [
Shape::Circle(2.0),
Shape::Rectangle { width: 3.0, height: 4.5 },
Shape::Point,
];
for s in &shapes {
println!("{:?} -> area {:.2}", s, s.area());
}
}match: all cases or it does not compile
match compares a value against a list of patterns and runs the arm that matches. The key feature is that it must be exhaustive: if you forget a variant, the compiler gives an error and tells you which one is missing. This means that when you add a new variant to the enum, the compiler will point out every match you must update, instead of leaving a silent bug. Since match is an expression, its result can be assigned to a variable. You can use the wildcard pattern _ for "everything else", and | to combine several patterns.
enum Command {
Quit,
Move { x: i32, y: i32 },
Write(String),
Color(u8, u8, u8),
}
fn describe(cmd: &Command) -> String {
match cmd {
Command::Quit => String::from("quit"),
Command::Move { x, y } if *x == 0 && *y == 0 => String::from("stay"),
Command::Move { x, y } => format!("move to ({x}, {y})"),
Command::Write(text) => format!("write '{text}'"),
Command::Color(r, g, b) => format!("color #{:02x}{:02x}{:02x}", r, g, b),
}
}
fn classify(n: i32) -> &'static str {
match n {
i32::MIN..=-1 => "negative",
0 => "zero",
1 | 2 | 3 => "small",
_ => "big",
}
}
fn main() {
let cmds = vec![
Command::Move { x: 3, y: -1 },
Command::Move { x: 0, y: 0 },
Command::Write(String::from("hi")),
Command::Color(255, 128, 0),
Command::Quit,
];
for c in &cmds {
println!("{}", describe(c));
}
println!("{} {} {} {}", classify(-5), classify(0), classify(2), classify(99));
}Notice several things in the code. The patterns destructure the data of each variant and bind names (x, y, text). The if condition after the pattern is called a guard and adds an extra condition. Ranges like 1..=3 and alternatives 1 | 2 | 3 work with numbers and characters. And the function classify returns a &'static str: a text literal that lives for the whole program; you will understand it better when you see lifetimes.
// Does NOT compile on purpose: non-exhaustive match
enum Light { Red, Yellow, Green }
fn main() {
let l = Light::Red;
let action = match l {
Light::Red => "stop",
Light::Green => "go",
// error[E0004]: pattern `Light::Yellow` not covered
};
println!("{action}");
}One last piece of advice about enums: think of them as a way to make invalid states impossible. Instead of a struct with a kind: String field and several optional fields that only make sense for each kind, define an enum whose variants carry exactly the data they need. That way the compiler guarantees you will never have, for example, a circle with a width. This style, called modeling with types, is one of the reasons Rust programs fail less in production.
enum Coin { Penny, Nickel, Dime, Quarter }
fn value_in_cents(coin: &Coin) -> u32 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
fn main() {
let purse = [Coin::Penny, Coin::Nickel, Coin::Dime, Coin::Quarter];
let mut total = 0;
for coin in &purse {
total += value_in_cents(coin);
}
println!("{total}");
}理解度チェック
問題 1 / 4What does it mean that match is exhaustive?
✎ マイノート
このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字