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

视频地址

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

源码地址

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

讲解内容

1、匹配字面值
例子:

let x = 1;
match x {
    1 => println!("one"),
    2 => println!("two"),
    3 => println!("three"),
    _ => println!("anything"),
}

2、匹配命名变量
例子:

fn main() {
    let x = Some(5);
    let y = 10;  //1处
    match x {
        Some(50) => println!("Got 50"),
        Some(y) => println!("Matched, y = {:?}", y), //此处的y和上面1处的y不一样,此处是引入的变量y覆盖之前的y
        _ => println!("Default case, x = {:?}", x),
    }
    println!("at the end: x = {:?}, y = {:?}", x, y);
}

3、多个模式
例子:

let x = 1;
match x {
    1 | 2 => println!("one or two"),
    3 => println!("three"),
    _ => println!("anything"),
}

说明: |表示或,即匹配1或者2

发布了132 篇原创文章 · 获赞 135 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/lcloveyou/article/details/104536337
今日推荐