rust - 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
.
解决方案
您可以像这样在模式匹配中解构结构:
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 章中。
推荐阅读
- reactjs - 在react js中遍历数组的对象
- c# - 如何在 asp.net-core 中使用代码优先迁移来删除唯一约束
- scroll - 一次显示多个图表。(Anylogic)
- vulkan - 在 Vulkan 中并排绘制颜色和深度图像
- java - 使用 OOP Deck of Cards Java 获取 null
- python - sqlite3绑定第一个项目
- kubernetes - GKE Nginx Ingress - 分配静态 IP
- java - 如何打印选择b系列的总和
- r - 计算不同组的固定年份的百分比变化
- react-native - 缩放到离用户位置最近的标记 react-native-maps