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

相关推荐
我是坏垠9 小时前
Crypto、Cipher与Password:Java加密开发的三个核心概念
java·开发语言·python
white_ant9 小时前
JDK LTS 版本升级迁移注意事项大全
java·开发语言
Bobolink_9 小时前
跨境业务网络环境评估,“干净、一致、独享”三个关键指标
开发语言·网络·php·跨境网络·网络环境
你怎么知道我是队长10 小时前
JavaScript的变量和数据类型介绍
开发语言·javascript·ecmascript
xingke10 小时前
C 语言多文件编程:(一)头文件、extern、编译链接
c语言·开发语言·多文件
戮漠summer10 小时前
Missing Semester 计算机教育中缺失的一课 Lecture 01 Shell
开发语言·后端·scala
jinyishu_11 小时前
C++ string使用方法
开发语言·c++
EW Frontier11 小时前
三级跳突破864维动作空间——QMIX-Hierarchical多无人机协同通信方法全解析【附python代码】
开发语言·python·无人机·强化学习·通信资源分配
名字还没想好☜11 小时前
Next.js 中间件实战:鉴权、重定向与 A/B 分流
开发语言·前端·javascript·中间件·react·next.js
乐观勇敢坚强的老彭11 小时前
C++浮点数使用注意事项
开发语言·c++