'outer:loop {println!("Entered the outer loop"); 'inner:loop {println!("Entered the inner loop");break 'outer; }println!("This point will never be reached");}println!("Exited the outer loop");
Match
Rust中的match表达式非常强大,首先看一个例子:
let day =5;match day {0|6=>println!("weekend"),1...5=>println!("weekday"), _ =>println!("invalid"),}
let x =1;match x { e @1...5=>println!("got a range element {}", e), _ =>println!("anything"),}
使用ref关键字来得到一个引用:
let x =5;letmut y =5;match x {// the `r` inside the match has the type `&i32`ref r =>println!("Got a reference to {}", r),}match y {// the `mr` inside the match has the type `&i32` and is mutablerefmut mr =>println!("Got a mutable reference to {}", mr),}
再看一个使用match表达式来解构元组的例子:
let pair = (0, -2);match pair { (0, y) =>println!("x is `0` and `y` is `{:?}`", y), (x, 0) =>println!("`x` is `{:?}` and y is `0`", x), _ =>println!("It doesn't matter what they are"),}
match的这种解构同样适用于结构体或者枚举。如果有必要, 还可以使用..来忽略域或者数据:
structPoint { x:i32, y:i32,}let origin =Point { x:0, y:0 };match origin {Point { x, .. } =>println!("x is {}", x),}enumOptionalInt {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."),}
此外,Rust还引入了if let和while let进行模式匹配:
let number =Some(7);letmut optional =Some(0);// If `let` destructures `number` into `Some(i)`, evaluate the block.ifletSome(i) = number {println!("Matched {:?}!", i);} else {println!("Didn't match a number!");}// While `let` destructures `optional` into `Some(i)`, evaluate the block.whileletSome(i) = optional {if i >9 {println!("Greater than 9, quit!"); optional =None; } else {println!("`i` is `{:?}`. Try again.", i); optional =Some(i +1); }}