How define filter func for both mut and not mut

Hello !
I would like define a filter func, like this:

fn foo(p: &&i32) -> bool {
    p.is_positive()
}

fn main() {
    let l: Vec<i32> = vec![];
    let mut ll: Vec<i32> = vec![];

    l.iter().filter(foo);
    ll.iter_mut().filter(foo);
}

But I can't use same fun for filter mut iter and not mut iter:

error[E0631]: type mismatch in function arguments
  --> src/main.rs:10:26
   |
1  | fn foo(p: &&i32) -> bool {
   | ------------------------ found signature of `for<'r, 's> fn(&'r &'s i32) -> _`
...
10 |     ll.iter_mut().filter(foo);
   |                          ^^^ expected signature of `for<'r> fn(&'r &mut i32) -> _`

Is that possible ? Thanks !

use std::ops::Deref;

fn foo<P: Deref<Target=i32>>(p: &P) -> bool {
    p.is_positive()
}
2 Likes

Nice ! Thanks !

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.