Exhaustive pattern matching is a Rust compiler rule requiring all enum variants to be handled in a match expression to prevent unhandled runtime errors.
Exhaustive pattern matching in Rust is a compiler requirement that forces you to handle every possible variant of an enum or data structure in a match expression. If you miss a case, the code will not compile, preventing runtime errors from unhandled states.
enum IpAddrKind {
V4,
V6,
}
fn route(ip_kind: IpAddrKind) {
match ip_kind {
IpAddrKind::V4 => println!("V4"),
IpAddrKind::V6 => println!("V6"),
}
}
Exhaustive pattern matching ensures your code accounts for every possible outcome of a decision. It acts like a strict checklist where the compiler refuses to let you run the program until you have written instructions for every single scenario. This prevents your software from crashing unexpectedly when it encounters a situation you forgot to plan for.