I want to implement a trait for closures of a certain type. Here is a minimal example ( playground ):
trait Foo { fn foo(&self, x: &u32); } impl<F> Foo for F where F: Fn(&u32) { fn foo(&self, x: &u32) { self(x) } } fn main() { let _: &FnOnce(&u32) = &|x| {};
This results in an error:
error: type mismatch resolving `for<'r> <[ closure@ <anon>:16:29: 16:35] as std::ops::FnOnce<(&'r u32,)>>::Output == ()`: expected bound lifetime parameter , found concrete lifetime [--explain E0271] --> <anon>:16:28 |> 16 |> let _: &Foo = &|x| {}; |> ^^^^^^^ note: required because of the requirements on the impl of `Foo` for `[ closure@ <anon>:16:29: 16:35]` note: required for the cast to the object type `Foo` error: type mismatch: the type `[ closure@ <anon>:16:29: 16:35]` implements the trait `std::ops::Fn<(_,)>`, but the trait `for<'r> std::ops::Fn<(&'r u32,)>` is required (expected concrete lifetime, found bound lifetime parameter ) [--explain E0281] --> <anon>:16:28 |> 16 |> let _: &Foo = &|x| {}; |> ^^^^^^^ note: required because of the requirements on the impl of `Foo` for `[ closure@ <anon>:16:29: 16:35]` note: required for the cast to the object type `Foo`
I have already tried explicitly adding HRTB to the where clause as follows:
where F: for<'a> Fn(&'a u32)
But it did not help. I also declared the lifetime in the impl block, for example:
impl<'a, F> Foo for F where F: Fn(&'a u32) { ... }
But this leads to a lifetime error in the impl block. I think these errors are correct and the lifetime parameter cannot be declared in the impl block.
How can I fix this example?
traits rust lifetime
Lukas Kalbertodt
source share