rust.jpeg
模式匹配是許多函數(shù)式編程語言(如Haskell或Scala) 的基礎(chǔ)和強大的構(gòu)建塊。對于最初接觸面向?qū)ο笳Z言來說,模式匹配是否有點陌生。
我們將無法像這些語言所提供的那樣,在復(fù)雜程度上復(fù)制模式匹配。盡管我們可以重用模式匹配的基本方法作為靈感來構(gòu)建一些有用的類型腳本。
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.
基本上,模式可以定義為描述事物可能一個或多個情況的。每個情況本身代表一個特定的行為,一旦情況匹配,就必須應(yīng)用該行為。
模式匹配
rust 語言中內(nèi)置了模式匹配,
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"),
}
}
函數(shù)參數(shù)匹配
fn print_location(&(x,y):&(u32,u32)){
println!("x = {},y={}",x,y)
}
fn main() {
let pnt = (3,5);
print_location(&pnt)