'traits bounds not satisfied on filter count method

I am practicing using closures in rust, but the second of these 2 codes does not work... when I extract the closure, the compiler tells me that some traits are not satisfied

this code work

let invalids = s.chars().filter(|c| c == &'a').count();

but not this one

let is_invalid = |c| c == &'a';
let invalids = s.chars().filter(is_invalid).count();

this gives me the following error

error[E0599]: the method `count` exists for struct `Filter<Chars<'_>, [closure@src/main.rs:4:24: 4:48]>`, but its trait bounds were not satisfied
  --> src/main.rs:5:63
   |
4  |   let is_valid_color = |c| c < &'a' && c > &'m';
   |                        ------------------------
   |                        |
   |                        doesn't satisfy `<_ as FnOnce<(&char,)>>::Output = bool`
   |                        doesn't satisfy `_: FnMut<(&char,)>`
5  |   let invalid_colors_count = s.chars().filter(is_valid_color).count();
   |                                                               ^^^^^ method cannot be called on `Filter<Chars<'_>, [closure@src/main.rs:4:24: 4:48]>` due to unsatisfied trait bounds
   |
  ::: /home/ryokugin/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/filter.rs:15:1
   |
15 | pub struct Filter<I, P> {
   | ----------------------- doesn't satisfy `_: Iterator`
   |
   = note: the following trait bounds were not satisfied:
           `<[closure@src/main.rs:4:24: 4:48] as FnOnce<(&char,)>>::Output = bool`
           which is required by `Filter<Chars<'_>, [closure@src/main.rs:4:24: 4:48]>: Iterator`
           `[closure@src/main.rs:4:24: 4:48]: FnMut<(&char,)>`
           which is required by `Filter<Chars<'_>, [closure@src/main.rs:4:24: 4:48]>: Iterator`
           `Filter<Chars<'_>, [closure@src/main.rs:4:24: 4:48]>: Iterator`
           which is required by `&mut Filter<Chars<'_>, [closure@src/main.rs:4:24: 4:48]>: Iterator`

Thanks :)



Solution 1:[1]

You need to assist with type info as Rust can not quite figure it out by itself in this case. The following works, where the type of the closure parameter is explicit:

    let is_invalid = |c: &char| c == &'a';
    let invalids = s.chars().filter(is_invalid).count();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Enselic