Rust 编程视频教程(进阶)——024_4 所有模式的语法 4
视频地址
头条地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/
源码地址
github地址:https://github.com/anonymousGiga/learn_rus...
讲解内容
1、匹配守卫提供的额外的条件
匹配守卫是一个指定于match分支模式之后的额外的if条件,它必须满足才能选择此分支。
例子1:
let num = Some(4);
match num {
Some(x) if x < 5 => println!("less than five: {}", x), //匹配守卫
Some(x) => println!("{}", x),
None => (),
}
例子2:
fn main() {
let x = Some(5);
let y = 10; //位置1
match x {
Some(50) => println!("Got 50"),
Some(n) if n == y => println!("Matched, n = {}", n), //此处的y就是位置1处的y,不是额外创建的变量
_ => println!("Default case, x = {:?}", x),
}
println!("at the end: x = {:?}, y = {}", x, y);
}
例子3:
let x = 4;
let y = false;
match x {
4 | 5 | 6 if y => println!("yes"), //等价于(4 | 5 | 6) if y => println!("yes"),
_ => println!("no"),
}
2、绑定
@运算符允许我们在创建一个存放值的变量,并且测试这个变量的值是否匹配模式。
例子:
enum Message {
Hello { id: i32 },
}
let msg = Message::Hello { id: 5 };
match msg {
Message::Hello { id: id_variable @ 3..=7 } => { //创建id_variable 存放id的值,同时测试值是否在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)
},
}
3、作业:自己编写一个使用@绑定并且测试值的例子。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: