Guide
Enums and match
Variants that carry a value, and a match the compiler will not let you leave open.
An enum is a closed set of cases and a variant may carry one value. Reading one is `match`, and the compiler will not let a case go unhandled.
Every case, named
A match that misses a variant is an error that names the variant rather than saying the match is not exhaustive, because the name is the answer you were about to go and look up.
// Enums and match: every case covered, checked by the compiler.
//
// A variant may carry one value. Leaving a case out is an error that names the case, rather than a
// run-time surprise on the one afternoon the light is amber.
enum Light {
Red
Amber
Green
}
enum Shape {
Dot
Circle(f32)
}
fn go(light: Light) -> bool {
return match light {
Red => false
Amber => false
Green => true
}
}
// `_` covers the rest, which is a decision rather than an oversight: it says the remaining cases
// are handled the same way, and it keeps saying that when a new variant is added.
fn describe(light: Light) -> String {
return match light {
Green => "go"
_ => "wait"
}
}
fn area(shape: Shape) -> f32 {
return match shape {
Dot => 0
Circle(radius) => radius * radius
}
}
What a missed case looks like
The same program with Amber left out. The alternative to this error is a surprise on the one afternoon the light is amber, in a build that has already shipped.
// Deliberately refused.
//
// A `match` must cover every variant, and the error names the ones it missed rather than saying
// "not exhaustive", which is the answer you were about to go and look up. `Amber` is missing here,
// and the alternative to this error is a run-time surprise on the one afternoon the light is amber.
enum Light {
Red
Amber
Green
}
fn go(light: Light) -> bool {
return match light {
Red => false
Green => true
}
}
The underscore is a decision
`_` covers the remaining cases and says they are handled the same way. It keeps saying that when a variant is added, which is exactly the trade: less noise now, no error later. Use it where the sentence is true and not to quiet the compiler.