rust常用的宏使用记录(九)

matches! 宏使用

rust 复制代码
matches! 是 Rust 标准库中一个非常有用的宏,它允许你方便地匹配一个表达式的结果是否符合某个模式。它的基本用法如下:


matches!(expression, pattern)
这个宏返回一个布尔值,如果 expression 匹配 pattern,则返回 true,否则返回 false。下面是一些常见的用法示例:

基本用法

let value = Some(3);
assert!(matches!(value, Some(3)));
匹配枚举

enum MyEnum {
    Foo,
    Bar(i32),
}

let e = MyEnum::Bar(10);
assert!(matches!(e, MyEnum::Bar(10)));
匹配并忽略值
使用 _ 忽略模式中的值:


let value = Some(42);
assert!(matches!(value, Some(_)));
多模式匹配
使用 | 运算符进行多模式匹配:


enum MyEnum {
    Foo,
    Bar,
    Baz,
}

let e = MyEnum::Bar;
assert!(matches!(e, MyEnum::Foo | MyEnum::Bar));
结合守卫(guard)
结合条件表达式使用:


let value = Some(4);
assert!(matches!(value, Some(x) if x > 3));
结合 Option 和 Result
rust
复制代码
let opt = Some(10);
assert!(matches!(opt, Some(x) if x > 5));

let res: Result<i32, &str> = Ok(2);
assert!(matches!(res, Ok(2)));
assert!(matches!(res, Err(_)));
结合结构体和元组

struct Point {
    x: i32,
    y: i32,
}

let p = Point { x: 1, y: 2 };
assert!(matches!(p, Point { x: 1, y: 2 }));
结合复杂模式

enum MyEnum {
    Foo(i32, i32),
    Bar { x: i32, y: i32 },
}

let e = MyEnum::Foo(1, 2);
assert!(matches!(e, MyEnum::Foo(1, 2)));

let e = MyEnum::Bar { x: 3, y: 4 };
assert!(matches!(e, MyEnum::Bar { x: 3, y: 4 }));
结合引用

let value = &Some(5);
assert!(matches!(value, &Some(5)));
这些示例展示了 matches! 宏的多种用法,涵盖了基本匹配、忽略值、多模式匹配、结合守卫、结构体匹配和复杂模式匹配等场景。matches! 宏的灵活性使得它在各种条件检查和模式匹配中都非常有用。
相关推荐
芒鸽6 小时前
macos上Rust 命令行工具鸿蒙化适配完全攻略
macos·rust·harmonyos
Smart-Space6 小时前
为pngme拓展加密功能与jpg格式支持
rust
古城小栈21 小时前
Rust Vec与HashMap全功能解析:定义、使用与进阶技巧
算法·rust
techdashen2 天前
Rust OnceCell 深度解析:延迟初始化的优雅解决方案
开发语言·oracle·rust
superman超哥2 天前
Serde 的零成本抽象设计:深入理解 Rust 序列化框架的哲学
开发语言·rust·开发工具·编程语言·rust序列化
星辰徐哥2 天前
Rust函数与流程控制——构建逻辑清晰的系统级程序
开发语言·后端·rust
superman超哥2 天前
序列化格式的灵活切换:Serde 生态的统一抽象力量
开发语言·rust·编程语言·rust serde·序列化格式·rust序列化格式
superman超哥2 天前
派生宏(Derive Macro)的工作原理:编译时元编程的艺术
开发语言·rust·开发工具·编程语言·rust派生宏·derive macro·rust元编程
superman超哥2 天前
处理复杂数据结构:Serde 在实战中的深度应用
开发语言·rust·开发工具·编程语言·rust serde·rust数据结构
superman超哥2 天前
错误处理与验证:Serde 中的类型安全与数据完整性
开发语言·rust·编程语言·rust编程·rust错误处理与验证·rust serde