rust - 将结构的多个字段与 `None` 匹配的最简单方法

标签 rust

我有一个像这样的 Rust 结构:

pub struct SomeMapping {
    pub id: String,
    pub other_id: Option<String>,
    pub yet_another_id: Option<String>,
    pub very_different_id: Option<String>
}

检查是否未设置所有可选 ID 的最简单方法是什么?我知道这样的语法

if let Some(x) = option_value {...}

Option 中提取值,但我不知道如何以简洁的方式使用它来检查 None 的多个值。

最佳答案

你可以像这样在模式匹配中解构一个结构:

pub struct SomeMapping {
    pub id: String,
    pub other_id: Option<String>,
    pub yet_another_id: Option<String>,
    pub very_different_id: Option<String>,
}

fn main() {
    let x = SomeMapping {
        id: "R".to_string(),
        other_id: Some("u".to_string()),
        yet_another_id: Some("s".to_string()),
        very_different_id: Some("t".to_string()),
    };

    if let SomeMapping {
        id: a,
        other_id: Some(b),
        yet_another_id: Some(c),
        very_different_id: Some(d),
    } = x {
        println!("{} {} {} {}", a, b, c, d);
    }
}

它记录在 Rust 书中 chapter 18 .

关于rust - 将结构的多个字段与 `None` 匹配的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58893899/

相关文章:

string - Cow<str> 切片的通用操作

generics - 使此函数通用时如何满足特征界限?

operator-overloading - 如何为不同的 RHS 类型和返回值重载运算符?

rust - 如何在Rust中为返回的元组设置静态生存期?

rust - 跨多个异步调用超时的最佳方法?

arrays - 为什么 println!仅适用于长度小于 33 的数组?

rust - 在 Rust 中 Scala 的 getOrElse 是什么?

python - 在 Rust 中使用 python 的多处理库

enums - 引用同一个文件时 rust 不同的类型

将 brainf*ck 代码解析为 Rust 中的树