与守卫的条件模式匹配
模式可以根据与使用 if
防护匹配的值无关的值进行匹配:
// Let's imagine a simplistic web app with the following pages:
enum Page {
Login,
Logout,
About,
Admin
}
// 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")
}
这将显示 不可用 。