模式匹配,多出现在函数式编程语言之中,为其复杂的类型系统提供一个简单轻松的解构能力。比如从enum等数据结构中取出数据等等,但是在书写上,相对比较复杂。我们来看一个例子:
Copy enum Direction {
East ,
West ,
North ,
South ,
}
fn main () {
let dire = Direction :: South ;
match dire {
Direction :: East => println! ( "East" ),
Direction :: North | Direction :: South => {
println! ( "South or North" );
},
_ => println! ( "West" ),
};
}
关于第二点,有的同学可能不明白。这么说吧,你可以把match整体视为一个表达式,既然是一个表达式,那么就一定能求得它的结果。因此,这个结果当然就可以被赋予一个变量咯。 看代码:
Copy enum Direction {
East ,
West ,
North ,
South ,
}
fn main () {
// let d_panic = Direction::South;
let d_west = Direction :: West ;
let d_str = match d_west {
Direction :: East => "East" ,
Direction :: North | Direction :: South => {
panic! ( "South or North" );
},
_ => "West" ,
};
println! ( "{}" , d_str);
}
Copy enum Action {
Say ( String ),
MoveTo ( i32 , i32 ),
ChangeColorRGB ( u16 , u16 , u16 ),
}
fn main () {
let action = Action :: Say ( "Hello Rust" . to_string ());
match action {
Action :: Say (s) => {
println! ( "{}" , s);
},
Action :: MoveTo (x, y) => {
println! ( "point from (0, 0) move to ({}, {})" , x, y);
},
Action :: ChangeColorRGB (r, g, _) => {
println! ( "change color into '(r:{}, g:{}, b:0)', 'b' has been ignored" ,
r, g,
);
}
}
}