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

相关推荐
2301_7766816522 分钟前
【用「概率思维」重新理解生活】
开发语言·人工智能·自然语言处理
熊大如如1 小时前
Java 反射
java·开发语言
ll7788111 小时前
C++学习之路,从0到精通的征途:继承
开发语言·数据结构·c++·学习·算法
我不想当小卡拉米2 小时前
【Linux】操作系统入门:冯诺依曼体系结构
linux·开发语言·网络·c++
heroboyluck2 小时前
rust 全栈应用框架dioxus server
rust·全栈·dioxus
teacher伟大光荣且正确2 小时前
Qt Creator 配置 Android 编译环境
android·开发语言·qt
炎芯随笔2 小时前
【C++】【设计模式】生产者-消费者模型
开发语言·c++·设计模式
乌鸦9442 小时前
《类和对象(下)》
开发语言·c++·类和对象+
炒空心菜菜2 小时前
SparkSQL 连接 MySQL 并添加新数据:实战指南
大数据·开发语言·数据库·后端·mysql·spark
多多*3 小时前
算法竞赛相关 Java 二分模版
java·开发语言·数据结构·数据库·sql·算法·oracle