Rust 编程视频教程(进阶)——024_4 所有模式的语法 4

视频地址

头条地址:https://www.ixigua.com/i6775861706447913485
B站地址:https://www.bilibili.com/video/av81202308/

源码地址

github地址:https://github.com/anonymousGiga/learn_rust

讲解内容

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、作业:自己编写一个使用@绑定并且测试值的例子。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值