match和deconstructuring解构

match和解构(destructuring)

tuple

1
2
3
4
5
6
7
8
9
let pair = (0, -2);

println!("Tell me about {:?}", pair);
match pair {
(0, y) => println!("First is `0` and `y` is `{:?}`", y),
(x, 0) => println!("`x` is `{:?}` and last is `0`", x),
_ => println!("It doesn't matter what they are"),
// `_` means don't bind the value to a variable
}

enum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
enum Color {
// These 3 are specified solely by their name.
Red,
Blue,
Green,
// These likewise tie `u32` tuples to different names: color models.
RGB(u32, u32, u32),
HSL(u32, u32, u32),
}

fn main() {
let color = Color::RGB(122, 17, 40);

match color {
Color::Red => println!("The color is Red!"),
Color::Blue => println!("The color is Blue!"),
Color::Green => println!("The color is Green!"),
Color::RGB(r, g, b) =>
println!("Red: {}, green: {}, and blue: {}!", r, g, b),
Color::HSL(h, s, l) =>
println!("Hue: {}, saturation: {}, lightness: {}!", h, s, l),
// Don't need another arm because all variants have been examined
}
}

指针引用的解构(pointer & ref)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let reference = &4; // equals: 'let ref reference = 4;'

match reference {
&val => println!("Got a value via destructuring: {:?}", val),
}

match *reference {
val => println!("Got a value via dereferencing: {:?}", val),
}
///也可以通过一个值,结构出它的引用对象
let mut mut_value = 5;
match mut_value {
ref mut m => {
// Got a reference. Gotta dereference it before we can
// add anything to it.
*m += 10;
println!("We added 10. `mut_value`: {:?}", m);
},
}

struct的解构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct Foo {
x: (u32, u32),
y: u32,
}
let foo = Foo { x: (1, 2), y: 3 };

match foo {
Foo { x: (1, b), y } => println!("First of x is 1, b = {}, y = {} ", b, y),

// you can destructure structs and rename the variables,
// the order is not important
Foo { y: 2, x: i } => println!("y is 2, i = {:?}", i),

// and you can also ignore some variables:
Foo { y, .. } => println!("y = {}, we don't care about x", y),
// this will give an error: pattern does not mention field `x`
//Foo { y } => println!("y = {}", y);
}

match guards(守卫)

1
2
3
4
5
6
7
8
9
10
11
12
fn main() {
let pair = (2, -2);

println!("Tell me about {:?}", pair);
match pair {
(x, y) if x == y => println!("These are twins"),
// The ^ `if condition` part is a guard
(x, y) if x + y == 0 => println!("Antimatter, kaboom!"),
(x, _) if x % 2 == 1 => println!("The first one is odd"),
_ => println!("No correlation..."),
}
}

绑定binding

当匹配一个范围的值时,如果想获得具体绑定的值,用@绑定符合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fn age() -> u32 {
15
}

fn main() {
println!("Tell me what type of person you are");

match age() {
0 => println!("I'm not born yet I guess"),
n @ 1 ..= 12 => println!("I'm a child of age {:?}", n),
n @ 13 ..= 19 => println!("I'm a teen of age {:?}", n),
n => println!("I'm an old person of age {:?}", n),
}
}

,
© 2023 PLAYAROUND All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero