注册 登录
电子工程世界-论坛 返回首页 EEWORLD首页 频道 EE大学堂 下载中心 Datasheet 专题
lugl4313820的个人空间 https://home.eeworld.com.cn/space-uid-1269709.html [收藏] [复制] [分享] [RSS]
日志

《Rust实战》match: 类型感知的模式匹配

已有 492 次阅读2024-4-16 15:55

2.4.7节中,引入一个新的match。

文中阐述了使用match更安全,代码看起来也是优雅而简洁,类似于其它语言的swtich关键字。但是他又优于C语言中的switch。match如果匹配到一个分支,match就立即返回。

给出了示例:

fn main() {
    let haystack = [1,1,2,5,14,42,132,429,1430,4862];
    for item in &haystack {
        let result = match item {
            42 | 132 => "hit!",
            _ => "miss!",
        };
        if result == "hit!" {
            println!("{}: {}",item, result);
        }
    }  
}

在上面的例程中,以 42 | 132的匹配 如果是真的就给出字符串 hit!,运行后效果如下:

    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/samp2_3`
42: hit!
132: hit!

到此我学习了for、while、loop、if 、else if 、else 、match,以及continue、break 循环标签'。使用这些流程控制语句,就可以在Rust的世界里玩了。

本文来自论坛,点击查看完整帖子内容。

评论 (0 个评论)

facelist doodle 涂鸦板

您需要登录后才可以评论 登录 | 注册

热门文章