rust match code example
Example 1: rust match string
match stringthing.as_str() {
"a" => println!("0"),
"b" => println!("1"),
"c" => println!("2"),
_ => println!("something else!"),
}
Example 2: matching in rust
match number {
1 => println!("One!"),
2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
13..=19 => println!("A teen"),
_ => println!("Ain't special"),
}
Example 3: rust match statement
#[derive(Debug)]
enum UsState {
Alabama,
Alaska,
}
#[derive(Debug)]
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
fn return_the_coin(coin:Coin) ->u8{
match coin{
Coin::Penny =>1,
Coin::Nickel =>10,
Coin::Dime =>15,
Coin::Quarter(state) =>{
println!("{:#?}",state);
25
}
}
}
fn main() {
let rtn=return_the_coin(Coin::Quarter(UsState::Alabama));
println!("{:#?}",rtn);
}
Example 4: rust pattern matching
fn main() {
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
_ => println!("anything"),
}
}