首页 > 解决方案 > Simplest way to match multiple fields of a struct against `None`

问题描述

I have a Rust struct like this:

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

What is the simplest way to check if all optional ids are not set? I know the syntax like

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

to extract a value from an Option, but I don't get how to use this in a concise way to check multiple values for None.

标签: rust

解决方案


您可以像这样在模式匹配中解构结构:

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 书籍第 18 章中。


推荐阅读