视频地址
头条地址:https://www.ixigua.com/i6775861706447913485
B站地址:https://www.bilibili.com/video/av81202308/
源码地址
github地址:https://github.com/anonymousGiga/learn_rust
讲解内容
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!");
}
网友评论