More elegant way to combine pattern matching and boolean condition
⚓ Rust 📅 2025-09-30 👤 surdeus 👁️ 12I just wrote this method on a struct:
pub fn tag(&self, key: &str) -> Option<&Attribute> {
self.tags().find(|attr| {
if let Attribute::Unknown { name, .. } = attr
&& name == key
{
true
} else {
false
}
})
}
I immensely dislike the if condition then true else false antipattern.
However,
pub fn tag(&self, key: &str) -> Option<&Attribute> {
self.tags().find(|attr| {
let Attribute::Unknown { name, .. } = attr && name == key
})
}
is syntactically invalid.
And
pub fn tag(&self, key: &str) -> Option<&Attribute> {
self.tags().find(|attr| {
if let Attribute::Unknown { name, .. } = attr {
name == key
} else {
false
}
})
}
still gives me antipattern vibes.
Is there a better way to write the above filter?
5 posts - 4 participants
🏷️ Rust_feed