Rust编程语言入门之模式匹配

农民  金牌会员 | 2023-4-22 16:28:44 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 911|帖子 911|积分 2733

模式匹配

模式


  • 模式是Rust中的一种特殊语法,用于匹配复杂和简单类型的结构
  • 将模式与匹配表达式和其他构造结合使用,可以更好地控制程序的控制流
  • 模式由以下元素(的一些组合)组成:

    • 字面值
    • 解构的数组、enum、struct 和 tuple
    • 变量
    • 通配符
    • 占位符

  • 想要使用模式,需要将其与某个值进行比较:

    • 如果模式匹配,就可以在代码中使用这个值的相应部分

一、用到模式(匹配)的地方

match 的 Arm
  1. match VALUE {
  2.   PATTERN => EXPRESSION,
  3.   PATTERN => EXPRESSION,
  4.   PATTERN => EXPRESSION,
  5. }
复制代码

  • match 表达式的要求:

    • 详尽(包含所有的可能性)

  • 一个特殊的模式:_(下划线):

    • 它会匹配任何东西
    • 不会绑定到变量
    • 通常用于 match 的最后一个 arm;或用于忽略某些值。

条件 if let 表达式


  • if let 表达式主要是作为一种简短的方式来等价的代替只有一个匹配项的 match
  • if let 可选的可以拥有 else,包括:

    • else if
    • else if let

  • 但,if let 不会检查穷尽性
  1. fn main() {
  2.   let favorite_color: Option<&str> = None;
  3.   let is_tuesday = false;
  4.   let age: Result<u8, _> = "34".parse();
  5.   
  6.   if let Some(color) = favorite_color {
  7.     println!("Using your favorite color, {}, as the background", color);
  8.   } else if if_tuesday {
  9.     println!("Tuesday is green day!");
  10.   } else if let Ok(age) = age {
  11.     if age > 30 {
  12.       println!("Using purple as the background color");
  13.     } else {
  14.       println!("Using orange as the background color");
  15.     }
  16.   } else {
  17.     println!("Using blue as the background color");
  18.   }
  19. }
复制代码
While let 条件循环


  • 只要模式继续满足匹配的条件,那它允许 while 循环一直运行
  1. fn main() {
  2.   let mut stack = Vec::new();
  3.   
  4.   stack.push(1);
  5.   stack.push(2);
  6.   stack.push(3);
  7.   
  8.   while let Some(top) = stack.pop() {
  9.     println!("{}", top);
  10.   }
  11. }
复制代码
for 循环


  • for 循环是Rust 中最常见的循环
  • for 循环中,模式就是紧随 for 关键字后的值
  1. fn main() {
  2.   let v = vec!['a', 'b', 'c'];
  3.   
  4.   for (index, value) in v.iter().enumerate() {
  5.     println!("{} is at index {}", value , index);
  6.   }
  7. }
复制代码
Let 语句


  • let 语句也是模式
  • let PATTERN = EXPRESSION
  1. fn main() {
  2.   let a = 5;
  3.   
  4.   let (x, y, z) = (1, 2, 3);
  5.   
  6.   let (q, w) = (4, 5, 6); // 报错 类型不匹配 3 2
  7. }
复制代码
函数参数


  • 函数参数也可以是模式
  1. fn foo(x: i32) {
  2.   // code goes here
  3. }
  4. fn print_coordinates(&(x, y): &(i32, i32)) {
  5.   println!("Current location: ({}, {})", x, y);
  6. }
  7. fn main() {
  8.   let point = (3, 5);
  9.   print_coordinates(&point);
  10. }
复制代码
二、可辩驳性:模式是否会无法匹配

模式的两种形式


  • 模式有两种形式:可辨驳的、无可辩驳的
  • 能匹配任何可能传递的值的模式:无可辩驳的

    • 例如:let x = 5;

  • 对某些可能得值,无法进行匹配的模式:可辩驳的

    • 例如:if let Some(x) = a_value

  • 函数参数、let 语句、for 循环只接受无可辩驳的模式
  • if let 和 while let 接受可辨驳和无可辩驳的模式
  1. fn main() {
  2.   let a: Option<i32> = Some(5);
  3.   let Some(x) = a: // 报错 None
  4.   if let Some(x) = a {}
  5.   if let x = 5 {} // 警告
  6. }
复制代码
三、模式语法

匹配字面值


  • 模式可直接匹配字面值
  1. fn main() {
  2.   let x = 1;
  3.   
  4.   match x {
  5.     1 => println!("one"),
  6.     2 => println!("two"),
  7.     3 => println!("three"),
  8.     _ => println!("anything"),
  9.   }
  10. }
复制代码
匹配命名变量


  • 命名的变量是可匹配任何值的无可辩驳模式
  1. fn main() {
  2.   let x = Some(5);
  3.   let y = 10;
  4.   
  5.   match x {
  6.     Some(50) => println!("Got 50"),
  7.     Some(y) => println!("Matched, y = {:?}", y),
  8.     _ => println!("Default case, x = {:?}", x),
  9.   }
  10.   
  11.   println!("at the end: x = {:?}, y = {:?}", x, y);
  12. }
复制代码
多重模式


  • 在match 表达式中,使用 | 语法(就是或的意思),可以匹配多种模式
  1. fn main() {
  2.   let x = 1;
  3.   
  4.   match x {
  5.     1 | 2 => println!("one or two"),
  6.     3 => println!("three"),
  7.     _ => println!("anything"),
  8.   }
  9. }
复制代码
使用 ..= 来匹配某个范围的值
  1. fn main() {
  2.   let x = 5;
  3.   match x {
  4.     1..=5 => println!("one through five"),
  5.     _ => println!("something else"),
  6.   }
  7.   
  8.   let x = 'c';
  9.   match x {
  10.     'a' ..='j' => println!("early ASCII letter"),
  11.     'k' ..='z' => println!("late ASCII letter"),
  12.     _ => println!("something else"),
  13.   }
  14. }
复制代码
解构以分解值


  • 可以使用模式来解构 struct、enum、tuple,从而引用这些类型值的不同部分
  1. struct Point {
  2.   x: i32,
  3.   y: i32,
  4. }
  5. fn main() {
  6.   let p = Point { x: 0, y: 7 };
  7.   
  8.   let Point { x: a, y: b } = p;
  9.   assert_eq!(0, a);
  10.   assert_eq!(7, b);
  11.   
  12.   let Point {x, y} = p;
  13.   assert_eq!(0, x);
  14.   assert_eq!(7, y);
  15.   
  16.   match p {
  17.     Point {x, y: 0} => println!("On the x axis at {}", x),
  18.     Point {x: 0, y} => println!("On the y axis at {}", y),
  19.     Point {x, y} => println!("On neither axis: ({}, {})", x, y),
  20.   }
  21. }
复制代码
解构 enum
  1. enum Message {
  2.   Quit,
  3.   Move {x: i32, y: i32},
  4.   Write(String),
  5.   ChangeColor(i32, i32, i32),
  6. }
  7. fn main() {
  8.   let msg = Message::ChangeColor(0, 160, 255);
  9.   
  10.   match msg {
  11.     Message::Quit => {
  12.       println!("The Quit variant has no data to destructure.")
  13.     }
  14.     Message::Move {x, y} => {
  15.       println!("Move in the x direction {} and in the y direction {}", x, y);
  16.     }
  17.     Message::Write(text) => println!("Text message: {}", text),
  18.     Message::ChangeColor(r, g, b) => {
  19.       println!("Change the color to red {}, green {}, and blue {}", r, g, b);
  20.     }
  21.   }
  22. }
复制代码
解构嵌套的 struct 和 enum
  1. enum Color {
  2.   Rgb(i32, i32, i32),
  3.   Hsv(i32, i32, i32),
  4. }
  5. enum Message {
  6.   Quit,
  7.   Move {x: i32, y: i32},
  8.   Write(String),
  9.   ChangeColor(Color),
  10. }
  11. fn main() {
  12.   let msg = Message::ChangeColor(Color::Hsv(0, 160, 255));
  13.   
  14.   match msg {
  15.     Message::ChangeClolr(Color::Rgb(r, g, b)) => {
  16.       println!("Change the color to red {}, green {}, and blur {}", r, g, b)
  17.     }
  18.     Message::ChangeColor(Color::Hsv(h, s, v)) => {
  19.       println!("Change the color to hue {}, saturation {}, and value {}", h, s, v)
  20.     }
  21.     _ => (),
  22.   }
  23. }
复制代码
解构 struct 和 tuple
  1. struct Point {
  2.   x: i32,
  3.   y: i32,
  4. }
  5. fn main() {
  6.   let ((feet, inches), Point {x, y}) = ((3, 10), Point {x: 3, y: -10});
  7. }
复制代码
在模式中忽略值


  • 有几种方式可以在模式中忽略整个值或部分值:

    • _
    • _ 配合其它模式
    • 使用以 _ 开头的名称
    • .. (忽略值的剩余部分)

使用 _ 来忽略整个值
  1. fn foo(_: i32, y: i32) {
  2.   println!("This code only uses the y parameter: {}", y);
  3. }
  4. fn main() {
  5.   foo(3, 4);
  6. }
复制代码
使用嵌套的 _ 来忽略值的一部分
  1. fn main() {
  2.   let mut setting_value = Some(5);
  3.   let new_setting_value = Some(10);
  4.   
  5.   match (setting_value, new_setting_value) {
  6.     (Some(_), Some(_)) => {
  7.       println!("Can't overwrite an existing customized value");
  8.     }
  9.     _ => {
  10.       setting_value = new_setting_value;
  11.     }
  12.   }
  13.   
  14.   println!("setting is {:?}", setting_value);
  15.   
  16.   
  17.   let numbers = (2, 4, 6, 8, 16, 32);
  18.   
  19.   match numbers {
  20.     (first, _, third, _, fifth) => {
  21.       println!("Some numbers: {}, {}, {}", first, third, fifth)
  22.     }
  23.   }
  24. }
复制代码
通过使用 _ 开头命名来忽略未使用的变量
  1. fn main() {
  2.   let _x = 5;
  3.   let y = 10;  // 创建未使用 警告
  4.   
  5.   let s = Some(String::from("Hello"));
  6.   
  7.   if let Some(_s) = s { // if let Some(_) = s {
  8.     println!("found a string");
  9.   }
  10.   
  11.   println!("{:?}", s); // 报错
  12. }
复制代码
使用 .. 来忽略值的剩余部分
  1. struct Point {
  2.   x: i32,
  3.   y: i32,
  4.   z: i32,
  5. }
  6. fn main() {
  7.   let origin = Point {x: 0, y: 0, z: 0};
  8.   match origin {
  9.     Point {x, ..} => println!("x is {}", x),
  10.   }
  11.   
  12.   let numbers = (2, 4, 8, 16, 32);
  13.   match numbers {
  14.     (first, .., last) => {
  15.       println!("Some numbers: {}, {}", first, last);
  16.     }
  17.   }
  18.   
  19.   match numbers {
  20.     (.., second, ..) => {  // 报错
  21.       println!("Some numbers: {}", second)
  22.     },
  23.   }
  24. }
复制代码
使用 match 守卫来提供额外的条件


  • match 守卫就是 match arm 模式后额外的 if 条件,想要匹配该条件也必须满足
  • match 守卫适用于比单独的模式更复杂的场景
例子一:
  1. fn main() {
  2.   let num = Some(4);
  3.   
  4.   match num {
  5.     Some(x) if x < 5 => println!("less than five: {}", x),
  6.     Some(x) => println!("{}", x),
  7.     None => (),
  8.   }
  9. }
复制代码
例子二:
  1. fn main() {
  2.   let x = Some(5);
  3.   let y = 10;
  4.   
  5.   match x {
  6.     Some(50) => println!("Got 50"),
  7.     Some(n) if n == y => println!("Matched, n = {:?}", n),
  8.     _ => println!("Default case, x = {:?}", x),
  9.   }
  10.   
  11.   println!("at the end: x = {:?}, y = {:?}", x, y);
  12. }
复制代码
例子三:
  1. fn main() {
  2.   let x = 4;
  3.   let y = false;
  4.   
  5.   match x {
  6.     4 | 5 | 6 if y => println!("yes"),
  7.     _ => println!("no"),
  8.   }
  9. }
复制代码
@绑定


  • @ 符号让我们可以创建一个变量,该变量可以在测试某个值是否与模式匹配的同时保存该值
  1. enum Message {
  2.   Hello {id: i32},
  3. }
  4. fn main() {
  5.   let msg = Message::Hello {id: 5};
  6.   
  7.   match msg {
  8.     Message::Hello {
  9.       id: id_variable @ 3..=7,
  10.     } => {
  11.       println!("Found an id in range: {}", id_variable)
  12.     }
  13.     Message::Hello {id: 10..=12} => {
  14.       println!("Found an id in another range")
  15.     }
  16.     Message::Hello {id} => {
  17.       println!("Found some other id: {}", id)
  18.     }
  19.   }
  20. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

农民

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表