在rust中,match的基本作用是解构。它能对tuple,enum,struct,ref,pointer等各种类型进行解构。但不同的类型,还是略有些不同。
一、一般的match
如tuple,enum,struct等。在这种情况下,match 需要覆盖全部情况。
更多的是进行分支判断,以下的例子见《Rust by Example》。
fn main() {
let pair = (0, -2);
// TODO ^ Try different values for `pair`
println!("Tell me about {:?}", pair);
// Match can be used to destructure a tuple
match pair {
// Destructure the second
(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
}
}
二、ref下的match
如ref,pointer等。在这种情况,感觉match往往是再做一个唯一的确定项。
1、更多的是进行解构。2、此外,match中并没有所有的可能情况出现,比如_
。
fn main() {
let reference = &4;
match reference {
&val => println!("Got a value via destructuring: {:?}", val),
}
// 特别有意思的是:
match (*reference)*2 {
val => println!("Got a value via dereferencing: {:?}", val), //=> 4*2=8
}
let _not_a_reference = 3;
let ref _is_a_reference = 3;
let value = 5;
let mut mut_value = 6;
match value {
ref r => println!("Got a reference to a value: {:?}", r),
}
match mut_value {
ref mut m => {
*m += 10;
println!("We added 10. `mut_value`: {:?}", m);
},
}
}