主頁 > 後端開發 > Rust編程語言入門之模式匹配

Rust編程語言入門之模式匹配

2023-04-23 07:31:37 後端開發

模式匹配

模式

  • 模式是Rust中的一種特殊語法,用于匹配復雜和簡單型別的結構
  • 將模式與匹配運算式和其他構造結合使用,可以更好地控制程式的控制流
  • 模式由以下元素(的一些組合)組成:
    • 字面值
    • 解構的陣列、enum、struct 和 tuple
    • 變數
    • 通配符
    • 占位符
  • 想要使用模式,需要將其與某個值進行比較:
    • 如果模式匹配,就可以在代碼中使用這個值的相應部分

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

match 的 Arm

match VALUE {
  PATTERN => EXPRESSION,
  PATTERN => EXPRESSION,
  PATTERN => EXPRESSION,
}
  • match 運算式的要求:
    • 詳盡(包含所有的可能性)
  • 一個特殊的模式:_(下劃線):
    • 它會匹配任何東西
    • 不會系結到變數
    • 通常用于 match 的最后一個 arm;或用于忽略某些值,

條件 if let 運算式

  • if let 運算式主要是作為一種簡短的方式來等價的代替只有一個匹配項的 match
  • if let 可選的可以擁有 else,包括:
    • else if
    • else if let
  • 但,if let 不會檢查窮盡性
fn main() {
  let favorite_color: Option<&str> = None;
  let is_tuesday = false;
  let age: Result<u8, _> = "34".parse();
  
  if let Some(color) = favorite_color {
    println!("Using your favorite color, {}, as the background", color);
  } else if if_tuesday {
    println!("Tuesday is green day!");
  } else if let Ok(age) = age {
    if age > 30 {
      println!("Using purple as the background color");
    } else {
      println!("Using orange as the background color");
    }
  } else {
    println!("Using blue as the background color");
  }
}

While let 條件回圈

  • 只要模式繼續滿足匹配的條件,那它允許 while 回圈一直運行
fn main() {
  let mut stack = Vec::new();
  
  stack.push(1);
  stack.push(2);
  stack.push(3);
  
  while let Some(top) = stack.pop() {
    println!("{}", top);
  }
}

for 回圈

  • for 回圈是Rust 中最常見的回圈
  • for 回圈中,模式就是緊隨 for 關鍵字后的值
fn main() {
  let v = vec!['a', 'b', 'c'];
  
  for (index, value) in v.iter().enumerate() {
    println!("{} is at index {}", value , index);
  }
}

Let 陳述句

  • let 陳述句也是模式
  • let PATTERN = EXPRESSION
fn main() {
  let a = 5;
  
  let (x, y, z) = (1, 2, 3);
  
  let (q, w) = (4, 5, 6); // 報錯 型別不匹配 3 2
}

函式引數

  • 函式引數也可以是模式
fn foo(x: i32) {
  // code goes here
}

fn print_coordinates(&(x, y): &(i32, i32)) {
  println!("Current location: ({}, {})", x, y);
}

fn main() {
  let point = (3, 5);
  print_coordinates(&point);
}

二、可辯駁性:模式是否會無法匹配

模式的兩種形式

  • 模式有兩種形式:可辨駁的、無可辯駁的
  • 能匹配任何可能傳遞的值的模式:無可辯駁的
    • 例如:let x = 5;
  • 對某些可能得值,無法進行匹配的模式:可辯駁的
    • 例如:if let Some(x) = a_value
  • 函式引數、let 陳述句、for 回圈只接受無可辯駁的模式
  • if let 和 while let 接受可辨駁和無可辯駁的模式
fn main() {
  let a: Option<i32> = Some(5);
  let Some(x) = a: // 報錯 None
  if let Some(x) = a {}
  if let x = 5 {} // 警告
}

三、模式語法

匹配字面值

  • 模式可直接匹配字面值
fn main() {
  let x = 1;
  
  match x {
    1 => println!("one"),
    2 => println!("two"),
    3 => println!("three"),
    _ => println!("anything"),
  }
}

匹配命名變數

  • 命名的變數是可匹配任何值的無可辯駁模式
fn main() {
  let x = Some(5);
  let y = 10;
  
  match x {
    Some(50) => println!("Got 50"),
    Some(y) => println!("Matched, y = {:?}", y),
    _ => println!("Default case, x = {:?}", x),
  }
  
  println!("at the end: x = {:?}, y = {:?}", x, y);
}

多重模式

  • 在match 運算式中,使用 | 語法(就是或的意思),可以匹配多種模式
fn main() {
  let x = 1;
  
  match x {
    1 | 2 => println!("one or two"),
    3 => println!("three"),
    _ => println!("anything"),
  }
}

使用 ..= 來匹配某個范圍的值

fn main() {
  let x = 5;
  match x {
    1..=5 => println!("one through five"),
    _ => println!("something else"),
  }
  
  let x = 'c';
  match x {
    'a' ..='j' => println!("early ASCII letter"),
    'k' ..='z' => println!("late ASCII letter"),
    _ => println!("something else"),
  }
}

解構以分解值

  • 可以使用模式來解構 struct、enum、tuple,從而參考這些型別值的不同部分
struct Point {
  x: i32,
  y: i32,
}

fn main() {
  let p = Point { x: 0, y: 7 };
  
  let Point { x: a, y: b } = p;
  assert_eq!(0, a);
  assert_eq!(7, b);
  
  let Point {x, y} = p;
  assert_eq!(0, x);
  assert_eq!(7, y);
  
  match p {
    Point {x, y: 0} => println!("On the x axis at {}", x),
    Point {x: 0, y} => println!("On the y axis at {}", y),
    Point {x, y} => println!("On neither axis: ({}, {})", x, y),
  }
}

解構 enum

enum Message {
  Quit,
  Move {x: i32, y: i32},
  Write(String),
  ChangeColor(i32, i32, i32),
}

fn main() {
  let msg = Message::ChangeColor(0, 160, 255);
  
  match msg {
    Message::Quit => {
      println!("The Quit variant has no data to destructure.")
    }
    Message::Move {x, y} => {
      println!("Move in the x direction {} and in the y direction {}", x, y);
    }
    Message::Write(text) => println!("Text message: {}", text),
    Message::ChangeColor(r, g, b) => {
      println!("Change the color to red {}, green {}, and blue {}", r, g, b);
    }
  }
}

解構嵌套的 struct 和 enum

enum Color {
  Rgb(i32, i32, i32),
  Hsv(i32, i32, i32),
}

enum Message {
  Quit,
  Move {x: i32, y: i32},
  Write(String),
  ChangeColor(Color),
}

fn main() {
  let msg = Message::ChangeColor(Color::Hsv(0, 160, 255));
  
  match msg {
    Message::ChangeClolr(Color::Rgb(r, g, b)) => {
      println!("Change the color to red {}, green {}, and blur {}", r, g, b)
    }
    Message::ChangeColor(Color::Hsv(h, s, v)) => {
      println!("Change the color to hue {}, saturation {}, and value {}", h, s, v)
    }
    _ => (),
  }
}

解構 struct 和 tuple

struct Point {
  x: i32,
  y: i32,
}

fn main() {
  let ((feet, inches), Point {x, y}) = ((3, 10), Point {x: 3, y: -10});
}

在模式中忽略值

  • 有幾種方式可以在模式中忽略整個值或部分值:
    • _
    • _ 配合其它模式
    • 使用以 _ 開頭的名稱
    • .. (忽略值的剩余部分)

使用 _ 來忽略整個值

fn foo(_: i32, y: i32) {
  println!("This code only uses the y parameter: {}", y);
}

fn main() {
  foo(3, 4);
}

使用嵌套的 _ 來忽略值的一部分

fn main() {
  let mut setting_value = https://www.cnblogs.com/QiaoPengjun/archive/2023/04/22/Some(5);
  let new_setting_value = Some(10);
  
  match (setting_value, new_setting_value) {
    (Some(_), Some(_)) => {
      println!("Can't overwrite an existing customized value");
    }
    _ => {
      setting_value = https://www.cnblogs.com/QiaoPengjun/archive/2023/04/22/new_setting_value;
    }
  }
  
  println!("setting is {:?}", setting_value);
  
  
  let numbers = (2, 4, 6, 8, 16, 32);
  
  match numbers {
    (first, _, third, _, fifth) => {
      println!("Some numbers: {}, {}, {}", first, third, fifth)
    }
  }
}

通過使用 _ 開頭命名來忽略未使用的變數

fn main() {
  let _x = 5;
  let y = 10;  // 創建未使用 警告
  
  let s = Some(String::from("Hello"));
  
  if let Some(_s) = s { // if let Some(_) = s {
    println!("found a string");
  }
  
  println!("{:?}", s); // 報錯 
}

使用 .. 來忽略值的剩余部分

struct Point {
  x: i32,
  y: i32,
  z: i32,
}

fn main() {
  let origin = Point {x: 0, y: 0, z: 0};
  match origin {
    Point {x, ..} => println!("x is {}", x),
  }
  
  let numbers = (2, 4, 8, 16, 32);
  match numbers {
    (first, .., last) => {
      println!("Some numbers: {}, {}", first, last);
    }
  }
  
  match numbers {
    (.., second, ..) => {  // 報錯
      println!("Some numbers: {}", second)
    },
  }
}

使用 match 守衛來提供額外的條件

  • match 守衛就是 match arm 模式后額外的 if 條件,想要匹配該條件也必須滿足
  • match 守衛適用于比單獨的模式更復雜的場景

例子一:

fn main() {
  let num = Some(4);
  
  match num {
    Some(x) if x < 5 => println!("less than five: {}", x),
    Some(x) => println!("{}", x),
    None => (),
  }
}

例子二:

fn main() {
  let x = Some(5);
  let y = 10;
  
  match x {
    Some(50) => println!("Got 50"),
    Some(n) if n == y => println!("Matched, n = {:?}", n),
    _ => println!("Default case, x = {:?}", x),
  }
  
  println!("at the end: x = {:?}, y = {:?}", x, y);
}

例子三:

fn main() {
  let x = 4;
  let y = false;
  
  match x {
    4 | 5 | 6 if y => println!("yes"),
    _ => println!("no"),
  }
}

@系結

  • @ 符號讓我們可以創建一個變數,該變數可以在測驗某個值是否與模式匹配的同時保存該值
enum Message {
  Hello {id: i32},
}

fn main() {
  let msg = Message::Hello {id: 5};
  
  match msg {
    Message::Hello {
      id: id_variable @ 3..=7,
    } => {
      println!("Found an id in range: {}", id_variable)
    }
    Message::Hello {id: 10..=12} => {
      println!("Found an id in another range")
    }
    Message::Hello {id} => {
      println!("Found some other id: {}", id)
    }
  }
}

本文來自博客園,作者:QIAOPENGJUN,轉載請注明原文鏈接:https://www.cnblogs.com/QiaoPengjun/p/17343139.html

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/550840.html

標籤:其他

上一篇:影像金字塔

下一篇:返回列表

標籤雲
其他(157837) Python(38092) JavaScript(25381) Java(17985) C(15215) 區塊鏈(8256) C#(7972) AI(7469) 爪哇(7425) MySQL(7137) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4557) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2430) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1959) Web開發(1951) HtmlCss(1919) python-3.x(1918) 弹簧靴(1913) C++(1910) xml(1889) PostgreSQL(1872) .NETCore(1854) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust編程語言入門之模式匹配

    模式匹配 模式 模式是Rust中的一種特殊語法,用于匹配復雜和簡單型別的結構 將模式與匹配運算式和其他構造結合使用,可以更好地控制程式的控制流 模式由以下元素(的一些組合)組成: 字面值 解構的陣列、enum、struct 和 tuple 變數 通配符 占位符 想要使用模式,需要將其與某個值進行比較 ......

    uj5u.com 2023-04-23 07:31:37 more
  • 影像金字塔

    影像金字塔 簡單來說就是 自下而上影像一步一步縮小 1 高斯金字塔(涉及高斯分布) 向下采樣(縮小,對金字塔來說是自下向上) 第一步: 高斯濾波去噪 第二部:將偶數行和列去掉 向上采樣(放大,對金字塔來說是自上向下) 第一步:在每個方向上擴大兩倍,新增的行和列填充0 第二步:利用之前同樣的內核進行卷 ......

    uj5u.com 2023-04-23 07:25:47 more
  • 影像邊緣檢測(Canny)

    Canny檢測的流程 Canny檢測主要是用于邊緣檢測 1)使用高斯濾波器,以平滑影像,濾除噪聲。 2)計算影像中每個像素點的梯度強度和方向。 3)應用非極大值(Non-Maximum Suppression)抑制,以消除邊緣檢測帶來的雜散回應 4)應用雙閾值(Double-Threshold)檢測 ......

    uj5u.com 2023-04-23 07:20:41 more
  • python| 關于excel的檔案處理

    創建一個成績單檔案score.xlsx,將平時成績單.xlsx檔案中對應班級作業表中學號和姓名列的內容寫入到score.xlsx中,并添加成績列,每個學生的成績采用隨機生成的一個分數填寫進去,最后統計所有學生的平均成績計算出來后,寫入到score.xlsx的最后一行最后一列之后的單元格中去。預想的步 ......

    uj5u.com 2023-04-23 07:19:54 more
  • java 發送 http 請求練習兩年半(HttpURLConnection)

    1、起一個 springboot 程式做 http 測驗: @GetMapping("/http/get") public ResponseEntity<String> testHttpGet(@RequestParam("param") String param) { System.out.pri ......

    uj5u.com 2023-04-22 07:35:28 more
  • Django筆記二十七之資料庫函式之文本函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十七之資料庫函式之文本函式 這篇筆記將介紹如何使用資料庫函式里的文本函式。 顧名思義,文本函式,就是針對文本欄位進行操作的函式,如下是目錄匯總: Concat() —— 合并 Left() —— 從左邊開始截取 Length() —— ......

    uj5u.com 2023-04-22 07:35:22 more
  • Rust中的Copy和Clone

    1.Copy和Clone Rust中的Copy和Clonetrait都允許創建型別實體的副本。它們都提供了一種復制型別實體的方法,但它們之間存在一些重要的區別。了解這些區別有助更好地使用這兩個特征。 2. Copytrait Copytrait允許按位復制型別的實體。這意味著當您將一個變數賦值給另一 ......

    uj5u.com 2023-04-22 07:35:17 more
  • LocalDateTime

    // LocalDateTime類: 獲取日期時間資訊。格式為 2018-09-06T15:33:56.750 // 得到指定日期時間 LocalDateTime dateTime = LocalDateTime.of(1985, 4, 15, 12, 12, 12); // 得到當前日期時間 Lo ......

    uj5u.com 2023-04-22 07:35:14 more
  • 圖片的腐蝕,膨脹,開丶閉運算,梯度計算,禮帽與黑帽

    1 腐蝕操作 用于圖片的去毛刺,內容削減 1 #腐蝕操作 2 #cv2.erode(src,kernel,iterations) 3 #src是圖片數字化陣列 4 #kernel則是一個盒,對該盒內的像素進行復試操作,值越小腐蝕能力越狠 5 #iterations是一個迭代次數,就是說你對這個圖片進 ......

    uj5u.com 2023-04-22 07:35:10 more
  • java獲取到heapdump檔案后,如何快速分析?

    原創:扣釘日記(微信公眾號ID:codelogs),歡迎分享,非公眾號轉載保留此宣告。 簡介 在之前的OOM問題復盤之后,本周,又一Java服務出現了記憶體問題,這次問題不嚴重,只會觸發堆記憶體占用高報警,沒有觸發OOM,但好在之前的復盤中總結了dump腳本,會在堆占用高時自動執行jstack與jmap ......

    uj5u.com 2023-04-22 07:34:51 more