Pattern matching in Rust is a very powerful control flow mechanism that allows you to handle conditional branching based on the structure and content of data. It is commonly implemented via the match statement, but can also be used with if let and while let constructs. Patterns can match literal values, destructure arrays, enums, structs, and more, while binding variables to parts of the pattern.
Basic Example
For example, we have a simple enum definition representing HTTP status codes:
rustenum HttpStatus { Ok, // 200 NotFound, // 404 Unknown(u16), // other status codes } fn main() { let status = HttpStatus::NotFound; match status { HttpStatus::Ok => println!("Request processed successfully."), HttpStatus::NotFound => println!("Page not found."), HttpStatus::Unknown(code) => println!("Unknown status code: {}", code), } }
In this example, the match statement checks the value of status and executes different code blocks based on its specific value. For HttpStatus::Unknown, we also destructure a u16 status code from it and print it out.
Advanced Application
Pattern matching can also be used with more complex data structures, such as structs and nested enums. For example, we can have a struct representing an HTTP request, which includes a HttpStatus field:
ruststruct HttpRequest { method: String, url: String, status: HttpStatus, } fn main() { let request = HttpRequest { method: "GET".to_string(), url: "/index.html".to_string(), status: HttpStatus::Ok, }; match request.status { HttpStatus::Ok => println!("{} request to {} processed successfully.", request.method, request.url), HttpStatus::NotFound => println!("{} request to {} not found.", request.method, request.url), HttpStatus::Unknown(code) => println!("{} request to {} encountered unknown status code: {}", request.method, request.url, code), } }
In this example, we use pattern matching to classify the HTTP request status and output different log messages based on the status.
Summary
Overall, pattern matching is one of the core features in Rust, providing a clear and powerful way to handle conditional logic. With pattern matching, we can write concise and maintainable code, which is especially useful when dealing with complex data structures.