Use boolean operators with repetitions in macro_rules

fn main() {
    let mut example = vec!["hello", "james", "london", "vertuoso", "logarithms", "lovable"];
    println!("{:#}", filter!(&mut example, "lo", "nd", "mes"))
}

#[macro_use]
#[macro_export]
macro_rules! filter {
    ($stories: expr, $($field: expr),+) => {
        $stories.iter().filter(|x| {
            $(
                x.contains($field)
            )+
        }).collect()
    }
}

This is a slightly simpler example of the macro I'm trying to create which will take in an arbitrary number of fields and filter the list based on whether it contains any of the fields.

In the above example, I would want to return ["hello", "london", "james"]. Is this possible? I tried calling filter() on each field and adding || to x.contains... but both do not compile.

You can add the operator like a separator in the repetition for contains -- close it with )||+ to put || between each expansion.

Your playground example then complains that your collect needs a type, perhaps something like collect::<Vec<_>>().

1 Like