21.18 Example of Nested Pattern Matching
Patterns can be deeply nested, matching multiple levels at once:
enum Connection { Tcp { ip: (u8, u8, u8, u8), port: u16 }, Udp { ip: (u8, u8, u8, u8), port: u16 }, Unix { path: String }, } fn main() { let conn = Connection::Tcp { ip: (127, 0, 0, 1), port: 8080 }; match conn { Connection::Tcp { ip: (127, 0, 0, 1), port } => { println!("Localhost with port {}", port); } Connection::Tcp { ip, port } => { println!("TCP {}.{}.{}.{}:{}", ip.0, ip.1, ip.2, ip.3, port); } Connection::Udp { ip, port } => { println!("UDP {}.{}.{}.{}:{}", ip.0, ip.1, ip.2, ip.3, port); } Connection::Unix { path } => { println!("Unix socket at {}", path); } } }
Here, Connection::Tcp { ip: (127, 0, 0, 1), port }
is a nested pattern that checks for a specific IP tuple while still binding port
.