let (a, ..) = x; // 用两个点,表示其他的全部省略 let (a, .., b) = x; // 用两个点,表示只省略所有元素也是可以的
match也是表达式
match除了匹配“结构”,还可以匹配“值”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
enum Direction { East, West, South, North } fn direction_to_int(x: Direction) -> i32 { match x { Direction::East => 10, Direction::West => 20, Direction::South => 30, Direction::North => 40, } } fn main() { let x = Direction::East; let s = direction_to_int(x); println! ("{}", s); }
我们可以使用或运算符|来匹配多个条件,比如:
1 2 3 4 5 6 7 8 9 10 11
fn category(x: i32) { match x { -1 | 1 => println! ("true"), 0 => println! ("false"), _ => println! ("error"), } } fn main() { let x = 1; category(x); }
使用..=表示一个闭区间范围:
1 2 3 4 5 6
let x = 'X'; match x { 'a' ..= 'z' => println! ("lowercase"), 'A' ..= 'Z' => println! ("uppercase"), _ => println! ("something else"), }
Guards
1 2 3 4 5 6 7 8 9 10
enum OptionalInt { Value(i32), Missing, } let x = OptionalInt::Value(5); match x { OptionalInt::Value(i) if i > 5 => println! ("Got an int bigger than five! "), OptionalInt::Value(..) => println! ("Got an int! "), OptionalInt::Missing => println! ("No such luck."), }
编译器没能完全覆盖住:
1 2 3 4 5 6 7
fn main() {//报错 let x = 10; match x { i if i > 5 => println! ("bigger than five"), i if i <= 5 => println! ("small or equal to five"), } }
必须加上
1
_ => unreachable! (),
变量绑定
如果x在[1,5]范围内,则将1绑定到变量e
1 2 3 4 5
let x = 1; match x { e @ 1 ..= 5 => println! ("got a range element {}", e), _ => println! ("anything"), }
嵌套层次比较深的绑定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#! [feature(exclusive_range_pattern)] fn deep_match(v: Option<Option<i32>>) -> Option<i32> { match v { // r 绑定到的是第一层 Option 内部,r 的类型是 Option<i32> // 与这种写法含义不一样:Some(Some(r)) if (1..10).contains(r) Some(r @ Some(1..10)) => r, _ => None, } } fn main() { let x = Some(Some(5)); println! ("{:? }", deep_match(x)); let y = Some(Some(100)); println! ("{:? }", deep_match(y)); }
‘|’表示所有都绑定
1 2 3 4 5
let x = 5; match x { e @ 1 .. 5 | e @ 8 .. 10 => println! ("got a range element {}", e), _ => println! ("anything"), }
ref和mut
有些晦涩难懂。。。啊啊啊啊。。。
函数和闭包参数做模式解构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
struct T { item1: char, item2: bool, } fn test( T{item1: arg1, item2: arg2} : T) { println! ("{} {}", arg1, arg2); } fn main() { let x = T { item1: 'A', item2: false, }; test(x); }