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之间的偶数,并且只在满足这两个条件时打印信息。

相关推荐
SomeOtherTime3 小时前
第 11 讲(大结局):编译期元编程与零拷贝架构——卫生声明宏(macro_rules!)、过程宏 AST 手术刀与 Serde 零反射序列化的终极合龙
rust
SomeOtherTime7 小时前
番外篇(第 12 讲):走向工业界深水区——从物理定律看 Rust 在真实工程中的“降维打击”与“阿喀琉斯之踵”
开发语言·rust
Kapaseker8 小时前
Rust 桌面开发到底怎么选?先看这篇文章!
rust
奶油话梅糖9 小时前
容器启停 2.5 毫秒:11 天 1,700 Star 的 Kiri,用一个 900 KB 的 PID 1 干掉了 runc 和 dockerd
前端·人工智能·rust
wflynn21 小时前
GitHub 今日推荐|kiri:clone3 系统调用直达容器,2.5 毫秒启动无 runc 中间层
docker·rust·kubernetes·开源·github·containers
SomeOtherTime1 天前
第 4 讲:突破静态枷锁——智能指针(Box/Rc/Arc)与内部可变性(Cell/RefCell/UnsafeCell)的内存暗道
rust
SomeOtherTime1 天前
第 9 讲:异步并发与 Pin 的底层解剖——async/await 无栈协程状态机脱糖、自引用死锁的终极救赎与 Future/Waker 驱动模型
rust
wflynn2 天前
GitHub 今日推荐|Stela:在 PC 上直接启动 macOS 的翻译层
rust·开源·github
aifannihao2 天前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib
鶴哥只手遮天2 天前
《rustc 内幕》第 1 章 全景:rustc 编译流水线与 crate 版图
后端·rust·开源