将结构体的多个字段与“None”进行匹配的最简单方法

Ach*_*him 4 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>
}
Run Code Online (Sandbox Code Playgroud)

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

if let Some(x) = option_value {...}
Run Code Online (Sandbox Code Playgroud)

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

edw*_*rdw 7

您可以在模式匹配中解构结构,如下所示:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

它记录在 Rust 书第 18 章中。