系列文章目錄
【跟小嘉學(xué) Rust 編程】一、Rust 編程基礎(chǔ)
【跟小嘉學(xué) Rust 編程】二、Rust 包管理工具使用
【跟小嘉學(xué) Rust 編程】三、Rust 的基本程序概念
【跟小嘉學(xué) Rust 編程】四、理解 Rust 的所有權(quán)概念
【跟小嘉學(xué) Rust 編程】五、使用結(jié)構(gòu)體關(guān)聯(lián)結(jié)構(gòu)化數(shù)據(jù)
【跟小嘉學(xué) Rust 編程】六、枚舉和模式匹配
【跟小嘉學(xué) Rust 編程】七、使用包(Packages)、單元包(Crates)和模塊(Module)來管理項(xiàng)目
【跟小嘉學(xué) Rust 編程】八、常見的集合
【跟小嘉學(xué) Rust 編程】九、錯(cuò)誤處理(Error Handling)
【跟小嘉學(xué) Rust 編程】十一、編寫自動(dòng)化測(cè)試
【跟小嘉學(xué) Rust 編程】十二、構(gòu)建一個(gè)命令行程序
【跟小嘉學(xué) Rust 編程】十三、函數(shù)式語言特性:迭代器和閉包
【跟小嘉學(xué) Rust 編程】十四、關(guān)于 Cargo 和 Crates.io
【跟小嘉學(xué) Rust 編程】十五、智能指針(Smart Point)
【跟小嘉學(xué) Rust 編程】十六、無畏并發(fā)(Fearless Concurrency)
【跟小嘉學(xué) Rust 編程】十七、面向?qū)ο笳Z言特性
【跟小嘉學(xué) Rust 編程】十八、模式匹配(Patterns and Matching)
前言
模式是Rust的一種特殊語法,用于匹配復(fù)雜的和簡(jiǎn)單類型的結(jié)構(gòu),模式與匹配表達(dá)式和其他構(gòu)造結(jié)合使用,可以更好的控制流。
模式由下列元素或組合組成
- 字面值
- 解構(gòu)的數(shù)組、enum、struct、tuple
- 變量
- 通配符
- 占位符
想要使用模式,需要將其與某個(gè)值進(jìn)行比較,如果模式匹配,就可以在代碼中使用這個(gè)值的想應(yīng)部分。
主要教材參考 《The Rust Programming Language》
一、 使用到模式的地方
1.1、match 分支
match VALUE {
PATTERN => EXPRESSION,
PATTERN => EXPRESSION,
PATTERN => EXPRESSION,
}
要求分支能夠詳盡所有可能性
特殊的模式: _
,匹配任何值,不會(huì)綁定到變量,通常用于match的最后一個(gè)分支,用于忽略某些值。
1.2、if let 條件表達(dá)式
if let 表達(dá)式主要是作為簡(jiǎn)短的方式來替代只有一個(gè)匹配項(xiàng)的match,if let 可選的可以擁有 else(else if 和 else if let),但是 if let 不會(huì)檢查窮盡性。
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, {color}, as the background");
} else if is_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");
}
}
1.3、while let 條件循環(huán)
只要模式繼續(xù)匹配就允許循環(huán)執(zhí)行。
let mut stack = Vec::new();
stack.push(1);
stack.push(2);
stack.push(3);
while let Some(top) = stack.pop() {
println!("{}", top);
}
1.4、for 循環(huán)
let v = vec!['a', 'b', 'c'];
for (index, value) in v.iter().enumerate() {
println!("{} is at index {}", value, index);
}
1.5、let 語句
let PATTERN = EXPRESSION;
let (x, y, z) = (1, 2, 3);
1.6、函數(shù)參數(shù)
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);
}
二、可辯駁性(Refutability)
可辯駁性:模式是否會(huì)無法匹配。
2.1、模式的兩種形式
- 模式有兩種形式:可辯駁的,無可辯駁的
- 能夠匹配任何可能傳遞的值的模式:無可辯駁的
- 對(duì)于某些可能的值,無法進(jìn)行匹配的模式:可辯駁的
- 函數(shù)參數(shù)、let 語句、for 循環(huán)只接受無可辯駁的模式
- if let 和while let 接受可辯駁的和無可辯駁的模式
三、模式匹配語法(Pattern Syntax)
3.1、模式匹配字面值(Matching Literals)
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
_ => println!("anything"),
}
3.2、匹配命名變量
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 = {y}", x);
3.3、多種模式
let x = 1;
match x {
1 | 2 => println!("one or two"),
3 => println!("three"),
_ => println!("anything"),
}
3.4、匹配范圍
示例:匹配數(shù)值范圍
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"),
}
3.5、解構(gòu)分解值
3.5.1、解構(gòu)結(jié)構(gòu)
示例:
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);
}
3.5.2、靈活匹配
fn main() {
let p = Point { x: 0, y: 7 };
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})");
}
}
}
3.5.3、解構(gòu)枚舉
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 {x} and in the y direction {y}");
}
Message::Write(text) => {
println!("Text message: {text}");
}
Message::ChangeColor(r, g, b) => {
println!("Change the color to red {r}, green {g}, and blue ",)
}
}
}
3.5.3、嵌套枚舉和結(jié)構(gòu)
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::ChangeColor(Color::Rgb(r, g, b)) => {
println!("Change color to red {r}, green {g}, and blue ");
}
Message::ChangeColor(Color::Hsv(h, s, v)) => {
println!("Change color to hue {h}, saturation {s}, value {v}")
}
_ => (),
}
}
3.5.4、解構(gòu)結(jié)構(gòu)和元組
let ((feet, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: -10 });
3.6、模式中忽略值
3.6.1、忽略某個(gè)值
fn foo(_: i32, y: i32) {
println!("This code only uses the y parameter: {}", y);
}
fn main() {
foo(3, 4);
}
3.6.2、忽略值的某一部分
范例1:
let mut setting_value = 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 = new_setting_value;
}
}
println!("setting is {:?}", setting_value);
范例2:
let numbers = (2, 4, 8, 16, 32);
match numbers {
(first, _, third, _, fifth) => {
println!("Some numbers: {first}, {third}, {fifth}")
}
}
3.6.3、忽略未使用變量警告
fn main() {
let _x = 5;
let y = 10;
let s = Some(String::from("Hello!"));
if let Some(_) = s {
println!("found a string");
}
println!("{:?}", s);
}
3.6.4、使用… 忽略值的剩余部分
struct Point {
x: i32,
y: i32,
z: i32,
}
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}");
}
}
3.6.5、match 守衛(wèi)
match 守衛(wèi)是 match 分支模式后額外的 if 條件,想要匹配該條件也必須滿足文章來源:http://www.zghlxwxcb.cn/news/detail-681236.html
let num = Some(4);
match num {
Some(x) if x % 2 == 0 => println!("The number {} is even", x),
Some(x) => println!("The number {} is odd", x),
None => (),
}
3.6.6、@ 綁定
enum Message {
Hello { id: i32 },
}
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),
}
總結(jié)
以上就是今天要講的內(nèi)容文章來源地址http://www.zghlxwxcb.cn/news/detail-681236.html
到了這里,關(guān)于【跟小嘉學(xué) Rust 編程】十八、模式匹配(Patterns and Matching)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!