Rust:@ 符号助你从容面对 match

@符号在Rust中是一个非常有用的特性,尤其是在需要在模式匹配中绑定变量时。以下是一些使用@的例子,展示了它在不同场景下的应用。

1. 绑定枚举变体的值

假设有一个枚举表示HTTP状态代码:

rust 复制代码
#[derive(Debug)]
enum HttpStatus {
    Ok,
    NotFound,
    Unauthorized,
    Unknown(u16), // 未知的状态代码
}

let status = HttpStatus::Unknown(501);

match status {
    HttpStatus::Ok => println!("Request succeeded"),
    code @ HttpStatus::Unknown(_) => {
        println!("Unknown status code encountered: {:?}", code);
    }
    _ => println!("Some other status"),
}

在这个例子中,我们使用@来绑定匹配到的HttpStatus::Unknown变体到变量code,这样我们就可以在打印消息中使用它了。

code @部分将整个匹配的枚举值绑定到变量code上,使我们能在后续的代码块中使用code变量。这里,如果status是一个Unknown变体,不管里面的数值是多少,都会执行打印操作,打印出code,即Unknown及其携带的数值。

2. 范围匹配并绑定值

当需要对一个范围内的值进行模式匹配并在匹配的分支中使用该值时,@也很有用:

rust 复制代码
let number = 9;

match number {
    n @ 1..=10 => println!("The number {} is between 1 and 10", n),
    _ => println!("The number is not in the range 1 to 10"),
}

这个例子演示了如何检查一个数字是否位于1到10之间,并在确认后打印出来。

3. 解构结构体并绑定整个结构体

如果你想要在模式匹配时解构一个结构体的一部分字段,同时又想保留对整个结构体的引用,@符号就非常有用:

rust 复制代码
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

let point = Point { x: 0, y: 7 };

match point {
   p @ Point { x, y: 0..=10 }  => {
        println!("Point is in range, x: {}, y: {}. Point: {:?}", x, p.y, p);
    }
    _ => println!("Point is out of range"),
}

这里,Point { x, y: 0..=10 } @ p不仅匹配了一个y值在0到10之间的点,而且还让我们能够通过p来引用整个Point实例。

4. 在模式守卫中使用

@也可以和模式守卫(if后面的条件表达式)结合使用,以提供更复杂的匹配逻辑:

rust 复制代码
let number = Some(42);

match number {
    Some(n @ 40..=50) if n % 2 == 0 => println!("The number is in the range and even: {}", n),
    _ => println!("The number does not match"),
}

在这个例子中,我们检查number是否是一个在40到50之间的偶数,并且只在满足这两个条件时打印信息。

相关推荐
Rust研习社1 小时前
Rust Clone 特征保姆级解读:显式复制到底怎么用?
开发语言·后端·rust
好家伙VCC20 小时前
**发散创新:基于Rust的轻量级权限管理库设计与开源许可证实践**在现代分布式系统中,**权限控制(RBAC
java·开发语言·python·rust·开源
@atweiwei20 小时前
用 Rust 构建agent的 LLM 应用的高性能框架
开发语言·后端·rust·langchain·eclipse·llm·agent
skilllite作者20 小时前
Spec + Task 作为「开发协议层」:Rust 大模型辅助的标准化、harness 化与可回滚
开发语言·人工智能·后端·安全·架构·rust·rust沙箱
zsqw1231 天前
以 Rust 为例,聊聊线性类型,以及整个类型系统
rust·编译器
Rust研习社1 天前
Rust Tracing 实战指南:从基础用法到生产级落地
rust
分布式存储与RustFS1 天前
MinIO迎来“恶龙”?RustFS这款开源存储简直“不讲武德”
架构·rust·开源·对象存储·minio·企业存储·rustfs
数据知道2 天前
claw-code 源码分析:从 TypeScript 心智到 Python/Rust——跨栈移植时类型、边界与错误模型怎么对齐?
python·ai·rust·typescript·claude code·claw code
Rust研习社2 天前
深入浅出 Rust 迭代器:从基础用法到性能优化
rust