頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/
github地址:https://github.com/anonymousGiga/learn_rus...
1、透過..進行匹配
例子1:
let x = 5;
match x {
1..=5 => println!("one through five"), //即匹配1到5的範圍
_ => println!("something else"),
}
說明:在例子中, 1..=5 等價於 1 | 2 | 3 | 4 | 5
例子2:
let x = 'c';
match x {
'a'..='j' => println!("early ASCII letter"),
'k'..='z' => println!("late ASCII letter"),
_ => println!("something else"),
}
2、解構並分解值
可以使用模式來解構結構體、列舉、元組和引用,以便使用這些值的不同部分。
(1)解構結構體
例子:
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);
}
說明:變數 a 和 b 來匹配結構體 p 中的 x 和 y 欄位。
也可以使用字面值作為結構體模式的一部分進行進行解構,而不是為所有的欄位建立變數。例子如下:
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),
}
}
(2)解構列舉型別
例子(複習):
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
)
}
}
}
說明:
對於 Message::Quit 這樣沒有任何資料的列舉成員,不能進一步解構其值。只能匹配其字面值 Message::Quit;
對於像 Message::Move 這樣的類結構體列舉成員,可以採用類似於匹配結構體的模式;
對於像 Message::Write 這樣的包含一個元素,以及像 Message::ChangeColor 這樣包含兩個元素的類元組列舉成員,其模式則類似於用於解構元組的模式。
(3)解構巢狀的結構體和列舉
例子:
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 the color to red {}, green {}, and blue {}",
r,
g,
b
)
}
Message::ChangeColor(Color::Hsv(h, s, v)) => {
println!(
"Change the color to hue {}, saturation {}, and value {}",
h,
s,
v
)
}
_ => ()
}
}
(4)解構結構體和元組
例子:
struct Point{
x: i32,
y: i32,
}
fn main() {
let ((feet, inches), Point {x, y}) = ((3, 10), Point { x: 3, y: -10 });
println!("feet = {}, inches = {}, x = {}, y = {}", feet, inches, x, y);
println!("Hello, world!");
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結