More elegant way to combine pattern matching and boolean condition

⚓ Rust    📅 2025-09-30    👤 surdeus    👁️ 12      

surdeus

Warning

This post was published 111 days ago. The information described in this article may have changed.

I 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

Read full topic

🏷️ Rust_feed