# 枚举和模式匹配 [参考链接](https://kaisery.github.io/trpl-zh-cn/ch06-00-enums.html) ## 枚举的定义 ```rust enum IpAddrKind { V4, V6, } ``` #### 枚举值 可以像这样创建 IpAddrKind 两个不同成员的实例: ```rust enum IpAddrKind { // V4, // V6, // 简化写法 V4(String), V6(String), V7(u8, u8, u8, u8) } // struct IpAddr { // kind: IpAddrKind, // address: String, // } fn main() { // let four = IpAddrKind::V4; // let five = IpAddrKind::V6; // route(IpAddrKind::V4); // route(IpAddrKind::V6); // let local = IpAddr { // kind: IpAddrKind::V4, // address: String::from("127.0.0.1"), // }; // let test = IpAddr { // kind: IpAddrKind::V6, // address: String::from("::1"), // }; let home = IpAddrKind::V4(String::from("127.0.0.1")); let test: = IpAddrKind::V6(String::from("::1")); let test = IpAddrKind::V7(127, 0, 0, 1); } fn route(ip: IpAddrKind) { } ``` ## match 控制流结构 ```rust enum Coin { Penny, Nickel, Dime, Quarter, } fn main() { let enter_value = value_in_enter(Coin::Dime); println!("The value of enter is: {}", enter_value) // The value of enter is: 100 } fn value_in_enter(coin: Coin) -> i8 { match coin { // 也可进行多代码执行 Coin::Quarter => { println!("Lucky Quarter"); 2 }, Coin::Penny => 5, Coin::Nickel => 50, Coin::Dime => 100, } } ``` #### 绑定值的模式 ```rust #[derive(Debug)] enum UsState { Alabama, Alaska, } enum Coin { Penny, Nickel, Dime, Quarter(UsState), } fn main() { let enter_value = value_in_enter(Coin::Dime); let enter_value = value_in_enter(Coin::Quarter(UsState::Alabama)); println!("The value of enter is: {}", enter_value) // The value of enter is: 100 } fn value_in_enter(coin: Coin) -> i8 { match coin { Coin::Quarter(state) => { println!("The value of state is: {:?} !", state); // The value of state is: Alabama ! 2 }, Coin::Penny => 5, Coin::Nickel => 50, Coin::Dime => 100, } } ``` #### 匹配 Option [参考链接](https://kaisery.github.io/trpl-zh-cn/ch06-02-match.html#%E5%8C%B9%E9%85%8D-optiont) [后续的直接查阅官网](https://kaisery.github.io/trpl-zh-cn/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html) > 代码案例依旧记录