6. Enum和Pattern matching
6.1 Enum枚举
IP地址枚举
enum IpAddr {
V4(String),
V6(String),
}
消息类型枚举:可以看到枚举中每个元素的类型可以不同
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
Option枚举
enum Option<T> {
None,
Some(T),
}
Option 的使用example
let some_number = Some(5);
let some_string = Some("a string");
let absent_number: Option<i32> = None;
6.2 模式匹配
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin { //此处有点像Java中的switch
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
fn main() {}
=> : curly brackets
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
_ 下划线代表剩下的所有case
let dice_roll = 9;
match dice_roll {
3 => add_fancy_hat(),
7 => remove_fancy_hat(),
_ => (),
}
fn add_fancy_hat() {}
fn remove_fancy_hat() {}
if let的使用
let config_max = Some(3u8);
if let Some(max) = config_max {
println!("The maximum is configured to be {}", max);
}
网友评论