- match 匹配
match 匹配
Rust 通过 match 关键字来提供模式匹配,用法和 C 语言的的 switch 类似。
fn main() {let number = 13;// 试一试 ^ 将不同的值赋给 `number`println!("Tell me about {}", number);match number {// 匹配单个值1 => println!("One!"),// 匹配多个值2 | 3 | 5 | 7 | 11 => println!("This is a prime"),// 匹配一个闭区间范围13...19 => println!("A teen"),// 处理其他情况_ => println!("Ain't special"),}let boolean = true;// match 也是一个表达式let binary = match boolean {// match 分支必须覆盖所有可能的值false => 0,true => 1,// 试一试 ^ 试着将其中一条分支注释掉};println!("{} -> {}", boolean, binary);}
