So, while playing around with crypto code, it seems that I have accidentally created a higher-order function which does not accept closure parameters. I would like to know how to fix this.
A minimal code example which reproduces the compiler error is this:
fn higher_order<F>(functor: &F) -> String
where F: Fn(&String) -> String
{
unimplemented!()
}
fn main() {
let closure = |s| unimplemented!();
println!("{}", higher_order(&closure));
}
For this example, the compiler errors are:
error[E0281]: type mismatch: the type `[closure@src/main.rs:8:19: 8:39]` implements the trait `std::ops::Fn<(_,)>`, but the trait `for<'r> std::ops::Fn<(&'r std::string::String,)>` is required (expected concrete lifetime, found bound lifetime parameter )
--> src/main.rs:9:20
|
9 | println!("{}", higher_order(&closure));
| ^^^^^^^^^^^^
|
= note: required by `higher_order`
error[E0271]: type mismatch resolving `for<'r> <[closure@src/main.rs:8:19: 8:39] as std::ops::FnOnce<(&'r std::string::String,)>>::Output == std::string::String`
--> src/main.rs:9:20
|
9 | println!("{}", higher_order(&closure));
| ^^^^^^^^^^^^ expected bound lifetime parameter , found concrete lifetime
|
= note: concrete lifetime that was found is lifetime '_#24r
= note: required by `higher_order`
error: aborting due to 2 previous errors
From the error messages and a couple of web searches, it looks like this originates from incorrect automatic lifetime inference and an appropriate lifetime annotation might be the solution, but all my attempts in this direction so far have failed.
EDIT: Even stranger, adding type annotations to the closure parameters will make the code compile:
fn higher_order<F>(functor: &F) -> String
where F: Fn(&String) -> String
{
unimplemented!()
}
fn main() {
let closure = |s: &String| unimplemented!();
println!("{}", higher_order(&closure));
}