Use nested patterns in a match expression to destructure enum variants and access inner data directly.
Use nested patterns inside a match arm to destructure data within enum variants or tuples directly. This allows you to access inner fields without creating intermediate variables.
enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
fn route(ip: IpAddr) {
match ip {
IpAddr::V4(a, b, c, d) => println!("V4: {}.{}.{}.{}", a, b, c, d),
IpAddr::V6(s) => println!("V6: {}", s),
}
}
Nested pattern matching lets you check the type of a value and immediately grab the data inside it in one step. Think of it like opening a specific box and instantly seeing the item inside without having to take the item out and put it on a table first. You use this whenever you need to handle different kinds of data that are wrapped inside a container.