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

相关推荐
追逐时光者1 分钟前
精选 8 个 .NET 开发实用的类库,效率提升利器!
后端·.net
CC.GG9 分钟前
【C++】AVL树
java·开发语言·c++
CoderCodingNo23 分钟前
【GESP】C++四级真题 luogu-B4416 [GESP202509 四级] 最长连续段
开发语言·c++·算法
a程序小傲26 分钟前
京东Java面试被问:Fork/Join框架的使用场景
java·开发语言·后端·postgresql·面试·职场和发展
想用offer打牌29 分钟前
面试官问Redis主从延迟导致脏数据读怎么解决?
redis·后端·面试
⑩-30 分钟前
Java四种线程创建方式
java·开发语言
月光在发光31 分钟前
22_GDB调试记录(未完成)
java·开发语言
222you32 分钟前
SpringAOP的介绍和入门
java·开发语言·spring
程序员zgh34 分钟前
代码重构 —— 读后感
运维·c语言·开发语言·c++·重构
liulilittle41 分钟前
moodycamel::ConcurrentQueue 清空队列的方法论
开发语言·c++