I have an enum with different variants and I want to find the first variant that matches then transform it by either returning the variant value or mapping it to something else.
In Scala, I'd use case classes to do something like:
data.collectFirst{ case d: DataD => d.data }
In Rust, I have to pattern match twice to achieve the same result. Is there a way to make it less verbose?
enum MyData {
DataA(String),
DataB(u64),
DataC(bool),
DataD { data: String, val: u32 },
}
fn main() {
// test data
let data = vec![
MyData::DataB(42),
MyData::DataD {
data: "meaning of life".to_owned(),
val: 42,
},
MyData::DataC(false),
];
// find first one that matches and map it
let found: Option<String> = data
.iter()
.find(|d| match **d {
MyData::DataD { .. } => true,
_ => false,
})
.and_then(|d| match *d {
MyData::DataD { ref data, .. } => Some(data.to_owned()),
_ => None,
});
}
filter_map(...).next()
, you can also usefind_map(...)
. – Ethanethane