In the example below, filter
works when passed a closure, but not when passed a function.
What can I do to make the function version work?
fn is_short(s: &str) -> bool {
s.len() <= 5
}
fn main() {
let months = "January|February|March|April|May|June|July|August";
//let short_names: Vec<&str> = months.split('|').filter(|m| m.len() <= 5).collect();
let short_names: Vec<&str> = months.split('|').filter(is_short).collect();
println!("short names = {:?}", short_names);
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0631]: type mismatch in function arguments
--> src/main.rs:9:59
|
1 | fn is_short(s: &str) -> bool {
| ---------------------------- found signature of `for<'r> fn(&'r str) -> _`
...
9 | let short_names: Vec<&str> = months.split('|').filter(is_short).collect();
| ^^^^^^^^ expected signature of `for<'r> fn(&'r &str) -> _`
error[E0599]: no method named `collect` found for struct `Filter<std::str::Split<'_, char>, for<'r> fn(&'r str) -> bool {is_short}>` in the current scope
--> src/main.rs:9:69
|
9 | let short_names: Vec<&str> = months.split('|').filter(is_short).collect();
| ^^^^^^^ method not found in `Filter<std::str::Split<'_, char>, for<'r> fn(&'r str) -> bool {is_short}>`
|
= note: the method `collect` exists but the following trait bounds were not satisfied:
`<for<'r> fn(&'r str) -> bool {is_short} as FnOnce<(&&str,)>>::Output = bool`
which is required by `Filter<std::str::Split<'_, char>, for<'r> fn(&'r str) -> bool {is_short}>: Iterator`
`for<'r> fn(&'r str) -> bool {is_short}: FnMut<(&&str,)>`
which is required by `Filter<std::str::Split<'_, char>, for<'r> fn(&'r str) -> bool {is_short}>: Iterator`
`Filter<std::str::Split<'_, char>, for<'r> fn(&'r str) -> bool {is_short}>: Iterator`
which is required by `&mut Filter<std::str::Split<'_, char>, for<'r> fn(&'r str) -> bool {is_short}>: Iterator`
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0599, E0631.
For more information about an error, try `rustc --explain E0599`.
error: could not compile `playground`
To learn more, run the command again with --verbose.