match绝对是Rust的亮点,其官网的首页也证明了这点。match终于告别switch时代,让人耳目一新。
不仅颜值高,而且是深不可测,用牛BHH来讲,是不过分。接下来,希望好好整一下。
1、替代老旧的if else.
match不仅能用在固定值的场合,带“范围”的也是没问题的。
不过,在这儿,用上了guard.
let temp =2.0_f32;
match temp {
x if x > 0_f32 => println!(">0"), //if x> 0=>guard模式
_ => println!("<=0"),
}
2、最佳的场合,enum
齐整呀!
enum Color {
// These 3 are specified solely by their name.
Red,
Blue,
Green,}
let color = Color::Red;
println!("What color is it?");
match color {
Color::Red => println!("The color is Red!"),
Color::Blue => println!("The color is Blue!"),
Color::Green => println!("The color is Green!"),
}
3、绑定
绝对完美!
let var =5_u32;
match age() {
0 => println!("I'm not born yet I guess"),
n @ 1 ... 12 => println!("I'm a child of age {:?}", n),
n @ 13 ... 19 => println!("I'm a teen of age {:?}", n),
n => println!("I'm an old person of age {:?}", n),
}