#Filter in function parameters

13 messages · Page 1 of 1 (latest)

onyx pawn
#

Hey everyone, is there any way I could do something like this:

/// Filter is like a predicate, it'd return a boolean
fn remove_element(array: &mut Vec<String>, filter: ?) {
    
}

fn main() {
    let mut array: Vec<String> = vec!["Hello, world!", "what's up world", "why would I", "sure"];
    
    remove_element(&array, {|e| e.contains("world")});
    // new array = {"why would I", "sure"}
}
#

Update doing, something like should work I guess:

fn remove_element<P>(array: &mut Vec<String>, filter: P>)
where
    P: FnMut(&String) -> bool)
{
    ...
}
#

Now is there any way I could invert the result of the predicate without having to be calling it?

#

So P is now inverted to !bool

dreamy basin
#

|x| !filter(x)

onyx pawn
#

alright, thanks 😦

gentle loom
#

What about using Vec::retain...?

#

This sounds essentially like that, but explicitly in-place and implemented for the struct...

onyx pawn
#

Yup, was using vec::retain, but this only removes the elements I still want
I plan to be using Vec::drain_filter

gentle loom
#

Well, you could use ! to invert that...

onyx pawn
#

yup, but I can't just invert the predicate

onyx pawn