Exhaustive matching is a Rust compiler rule requiring all enum variants to be handled in a match expression to prevent unhandled cases.
Exhaustive matching requires a match expression to handle every possible variant of an enum or pattern, ensuring no cases are left unhandled at compile time.
enum IpAddrKind {
V4,
V6,
}
fn route(ip_kind: IpAddrKind) {
match ip_kind {
IpAddrKind::V4 => println!("V4"),
IpAddrKind::V6 => println!("V6"),
}
}
If you omit a variant, the compiler will refuse to compile the code until all possibilities are covered.
Exhaustive matching is a safety rule that forces you to handle every possible outcome of a decision. It prevents your program from crashing later by ensuring you've planned for every scenario before the code even runs. Think of it like a vending machine that must have a specific slot for every type of coin; if a new coin type is added, the machine won't work until a slot is built for it.