我有一个像这样的 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/