模式匹配是许多函数式编程语言(如Haskell或Scala) 的基础和强大的构建块。对于最初接触面向对象语言来说,模式匹配是否有点陌生。
我们将无法像这些语言所提供的那样,在复杂程度上复制模式匹配。尽管我们可以重用模式匹配的基本方法作为灵感来构建一些有用的类型脚本。
Essentially a pattern can be defined as a thing describing one or more cases. Each case itself represents a specific behavior which has to be applied once the case matches.
基本上,模式可以定义为描述事物可能一个或多个情况的。每个情况本身代表一个特定的行为,一旦情况匹配,就必须应用该行为。
模式匹配
rust 语言中内置了模式匹配,
fn main() {
let x = 5;
match x {
1..=5 => println!("1..5"),
_ => println!("others")
}
}
#[derive(Debug)]
enum PlayerAction {
Quit,
Move{x:u32,y:u32},
speak(String),
}
fn main() {
let action = PlayerAction::Move{x:5,y:3};
match action {
PlayerAction::Quit => println!("player quit mae"),
PlayerAction::Move{x,y} => println!("player move {},{}",x,y),
PlayerAction::speak(s) => println!("speak {}",&s),
}
enum Message {
Hello { id: i32 },
}
fn main(){
let msg = Message::Hello { id: 5 };
match msg {
Message::Hello { id: id_variable @ 3..=7 } => {
println!("Found an id in range: {}", id_variable)
},
Message::Hello { id: 10..=12 } => {
println!("Found an id in another range")
},
Message::Hello { id } => {
println!("Found some other id: {}", id)
},
}
}
fn main(){
let x = 2;
let y = true;
match x {
4 | 5 | 6 if y => println!("yes"),
_ => println!("no"),
}
}
函数参数匹配
fn print_location(&(x,y):&(u32,u32)){
println!("x = {},y={}",x,y)
}
fn main() {
let pnt = (3,5);
print_location(&pnt)
网友评论