定义
enum IpAddrkind {
V4,
V6,
}
struct IpAddr {
kind: IpAddrkind,
address: String,
}
使用
注意枚举的成员位于其标识符的命名空间中,并使用两个冒号分开。
let four = IpAddrkind::V4;
let six = IpAddrkind::V6;
let home = IpAddr {
kind: IpAddrkind::V4,
address: String::from("127.0.0.1"),
};
let loopback = IpAddr {
kind: IpAddrkind::V6,
address: String::from("::1"),
};
更简洁的方式
enum IpAddress {
V4(String),
V6(String),
}
let home = IpAddress::V4(String::from("127.0.0.1"));
let loopback = IpAddress::V6(String::from("::1"));
优化版本,让代码有更多的意义
enum Ip {
V4(u8, u8, u8, u8),
V6(String),
}
let home = Ip::V4(127, 0, 0, 0);
let loopback = Ip::V6(String::from("::1"));
嵌入多种类型
// Quit 没有关联任何数据。
// Move 包含一个匿名结构体。
// Write 包含单独一个 String。
// ChangeColor 包含三个 i32。
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
let m = Message::Write(String::from("hello"));
m.call();
// 结构体和枚举还有另一个相似点:就像可以使用 impl 来为结构体定义方法那样,也可以在枚举上定义方法。
impl Message {
fn call(&self) {}
}
Option 枚举和其相对于空值的优势
Rust 中没有空值,不过它确实拥有一个可以编码存在或不存在概念的枚举。这个枚举是 Option
let some_number = Some(5);
let some_string = Some("a string");
let absent_number: Option = None;
println!("{:?}, {:?}, {:?}", some_number, some_string, absent_number);
match 控制流运算符
let res = value_in_cents(Coin::Penny);
println!("res:{:?}", res);
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => {
println!("Lucky penny!");
1
}
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
绑定值的模式
let res = value_in_cents1(Coin1::Quarter(UsState::Alabama));
println!("res = {}", res);
fn value_in_cents1(coin: Coin1) -> u8 {
match coin {
Coin1::Penny => {
println!("Lucky penny!");
1
}
Coin1::Nickel => 5,
Coin1::Dime => 10,
Coin1::Quarter(state) => {
println!("State quarter from {:?}!", state);
25
}
}
}
#[derive(Debug)]
enum UsState {
Alabama,
Alaska,
}
enum Coin1 {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
匹配 Option
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
println!("five = {:?}, six = {:?}, none = {:?}", five, six, none);
fn plus_one(x: Option) -> Option {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
_ 通配符
可以使用特殊的模式 _ 替代 默认
let some_u8_value = 0u8;
match some_u8_value {
1 => println!("one"),
3 => println!("three"),
5 => println!("five"),
7 => println!("seven"),
_ => println!("Ignore"),
}
if let 简单控制流
let some_u8_value = Some(0u8);
println!("{:?}", some_u8_value);
match some_u8_value {
Some(3) => println!("theree"),
_ => (),
}
简洁写法
if let Some(3) = some_u8_value {
println!("Three");
} else {
println!("Default");
}
可以认为 if let 是 match 的一个语法糖
let coin = Coin1::Quarter(UsState::Alabama);
let mut count = 0;
match coin {
Coin1::Quarter(state) => println!("State quarter from {:?}!", state),
_ => count += 1,
}
用if let 写法
let coin = Coin1::Quarter(UsState::Alaska);
if let Coin1::Quarter(state) = coin {
println!("State quarter from {:?}!", state);
} else {
count += 1;
}