Enums and Match
Enum variants, payloads, wildcard arms, and match expressions.
Enums can carry payloads, and match can destructure variants.
enum Shape {
Circle(radius: f32),
Rect(w: f32, h: f32),
Point,
}
fn area(shape: Shape) -> f32 {
return match shape {
.Circle(r) => r * r * 3.14,
.Rect(w, h) => w * h,
.Point => 0.0,
_ => 0.0,
};
}
Construct a variant with the enum name and a payload literal:
fn main() {
let shape = Shape.Circle { radius: 2.0 };
assert area(shape) > 12.0;
}
Enums may also use an integer backing type when the tag representation matters:
enum Color: u8 {
Red = 1,
Green = 2,
Blue = 3,
}
match expr { ... } is supported for enums, integers, and strings. Current
patterns include integer and string literals, enum variants, enum payload
bindings, and _ wildcard.
let value = match x {
1 => 10,
2 => { return 20; },
_ => 0,
};
In expression contexts, all arms must produce compatible result types. A block arm must return the arm value:
let value = match x {
1 => {
return 10;
}
_ => 0,
};
Enum matches are checked for exhaustiveness unless a wildcard arm is present:
enum Status {
Ready,
Blocked,
}
fn code(status: Status) -> i32 {
return match status {
.Ready => 1,
.Blocked => 2,
};
}
For integer and string matches, include _ because the compiler cannot list
every possible value:
fn label(value: i32) -> str {
return match value {
1 => "one",
2 => "two",
_ => "many",
};
}
Payload arms bind values positionally:
enum Result {
Ok(value: i32),
Err(message: str),
}
fn value_or_zero(result: Result) -> i32 {
return match result {
.Ok(value) => value,
.Err(_) => 0,
};
}
Use _ to ignore a payload. ._ is not a pattern; the wildcard is always just
_.