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 可以让你的代码更简洁、更易读。

相关推荐
程序员爱钓鱼6 分钟前
Go 编程实战:闭包 Closure——函数如何记住外部变量
后端·google·go
JaguarJack7 分钟前
NativePHP v4 让 Blade 构建原生 iOS 与 Android 界面
后端·php·服务端
李妍.8 小时前
02Numpy基础(上)
开发语言·python
TheBestRucy8 小时前
Python 九阳神功之贰:面向对象(下)
开发语言·python
AI_小站9 小时前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
笃行35010 小时前
向量数据库单独建一套,这笔账划不划算
后端
felixking10 小时前
C++20 协程
开发语言·c++·协程
weixin_4316004410 小时前
Agent Workflow 学习向:Code 节点,比模板更强的变量加工
后端·python·学习·ai·
Rain的Java大神之路10 小时前
短信接口被狂刷怎么处理
java·运维·后端·web安全·面试·架构·xss
Zane19941211 小时前
CAS 与原子类:Java 如何实现无锁编程
java·开发语言