Rust 中的 match 基本用法

Rust 中的 match 是一个强大的控制流运算符,它允许你将一个值与一系列的模式进行匹配,并根据匹配的模式执行代码。以下是 match 的基本用法:

基础语法

复制代码
match value {
    模式1 => 表达式1,
    模式2 => 表达式2,
    _ => 默认表达式,
}

示例

下面的例子中,我们匹配一个枚举类型的变量:

复制代码
enum Direction {
    Up,
    Down,
    Left,
    Right,
}

fn main() {
    let direction = Direction::Up;

    match direction {
        Direction::Up    => println!("Going up!"),
        Direction::Down  => println!("Going down!"),
        Direction::Left  => println!("Going left!"),
        Direction::Right => println!("Going right!"),
    }
}

匹配字面值

复制代码
let x = 1;

match x {
    1 => println!("One"),
    2 => println!("Two"),
    3 => println!("Three"),
    _ => println!("Anything"),
}

匹配命名变量

复制代码
let x = Some(5);
let y = 10;

match x {
    Some(50) => println!("Got 50"),
    Some(y) => println!("Matched, y = {:?}", y), // 注意这里 `y` 的值是 5
    _ => println!("Default case, x = {:?}", x),
}

println!("at the end: x = {:?}, y = {:?}", x, y); // y 的值仍然是 10

匹配多个模式

可以用 | 来匹配多个模式:

复制代码
let x = 1;

match x {
    1 | 2 => println!("One or two"),
    3 => println!("Three"),
    _ => println!("Anything"),
}

通过匹配来解构

可以匹配复合数据类型,如元组、枚举、结构体等,并解构它们的值:

复制代码
let pair = (2, -2);

match pair {
    (x, y) if x == y => println!("These are twins"),
    (x, y) if x + y == 0 => println!("Antimatter, kaboom!"),
    (x, _) if x % 2 == 1 => println!("The first one is odd"),
    _ => println!("No correlation..."),
}

match 必须穷尽所有情况

在 Rust 中,match 必须覆盖所有可能的值,除非使用 _ 通配符来处理剩余的情况。

复制代码
let x = 0;

match x {
    1 => println!("one"),
    2 => println!("two"),
    _ => println!("anything"), // `_` 是一个特殊的模式,可以匹配任何值
}

以上就是 match 的基本用法。合理使用 match 可以让你的代码更简洁、更易读。

相关推荐
Emma歌小白18 分钟前
完整后台模块模板
后端
得物技术21 分钟前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
Emma歌小白23 分钟前
配套后端(Node.js + Express + SQLite)
后端
isysc11 小时前
面了一个校招生,竟然说我是老古董
java·后端·面试
uhakadotcom1 小时前
静态代码检测技术入门:Python 的 Tree-sitter 技术详解与示例教程
后端·面试·github
幂简集成explinks1 小时前
e签宝签署API更新实战:新增 signType 与 FDA 合规参数配置
后端·设计模式·开源
River4161 小时前
Javer 学 c++(十三):引用篇
c++·后端
RoyLin1 小时前
TypeScript设计模式:迭代器模式
javascript·后端·node.js
爱海贼的无处不在2 小时前
一个需求竟然要开14个会:程序员的日常到底有多“会”?
后端·程序员