structPoint{x: i32,y: i32,}fnmain(){letp=Point{x:0,y:7}letPoint{x:a,y:b}=p// 或者
letPoint{a,b}=passert_eq(0,a);assert_eq(7,b);// 模式匹配
matchp{Point{x,y: 0}=>println!("On the x asis at {x}")Point{x: 0,y}=>println!("On the y asis at {y}")Point{x,y}=>println!("On neither axis: ({x}, {y})")}}
enumMessage{Quit,Move{x: i32,y: i32},Write(String),ChangeColor(i32,i32,i32),}fnmain(){letmsg=Message::ChangeColor(0,160,255);matchmsg{Message::Quit=>{println!("The Quit variant has no data to destructure.");}Message::Move{x,y}=>{println!("Move in the x direction {x} and in the y direction {y}");}Message::Write(text)=>{println!("Text message: {text}");}Message::ChangeColor(r,g,b)=>{println!("Change the color to red {r}, green {g}, and blue {b}",)}}}
enumColor{Rgb(i32,i32,i32),Hsv(i32,i32,i32),}enumMessage{Quit,Move{x: i32,y: i32},Write(String),ChangeColor(Color),}fnmain(){letmsg=Message::ChangeColor(Color::Hsv(0,160,255));matchmsg{// 嵌套枚举值的match
Message::ChangeColor(Color::Rgb(r,g,b))=>{println!("Change color to red {r}, green {g}, and blue {b}");}Message::ChangeColor(Color::Hsv(h,s,v))=>{println!("Change color to hue {h}, saturation {s}, value {v}")}_=>(),}}
letnum=Some(4);matchnum{// 当Some(x) 枚举模式,并且 x 为偶数
Some(x)ifx%2==0=>println!("The number {} is even",x),Some(x)=>println!("The number {} is odd",x),None=>(),}
@运算符绑定
允许在创建一个存放值的变量的同时,测试其值是否匹配模式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
enumMessage{Hello{id: i32},}letmsg=Message::Hello{id: 5};matchmsg{Message::Hello{id: id_variable@3..=7,// 创建变量 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),}