Rust Pattern Matching Conditional pattern matching with guards


Patterns can be matched based on values independent to the value being matched using if guards:

// Let's imagine a simplistic web app with the following pages:
enum Page {

// We are authenticated
let is_authenticated = true;

// But we aren't admins
let is_admin = false;

let accessed_page = Page::Admin;

match accessed_page {
    // Login is available for not yet authenticated users
    Page::Login if !is_authenticated => println!("Please provide a username and a password"),

    // Logout is available for authenticated users 
    Page::Logout if is_authenticated => println!("Good bye"),
    // About is a public page, anyone can access it
    Page::About => println!("About us"),

    // But the Admin page is restricted to administators
    Page::Admin if is_admin => println!("Welcome, dear administrator"),

    // For every other request, we display an error message
    _ => println!("Not available")

This will display "Not available".