Hello,
I want to create a trait that defines in which way a parameter T
is passed to a Fn
after it was passed by value:
trait Foo{
type Bar<'a, T: 'a>;
fn foo<T, FN: for<'a> Fn(Self::Bar<'a, T>)>(t: T, f: FN);
}
impl Foo for (){
type Bar<'a, T: 'a> = &'a T;
fn foo<T, FN: for<'a> Fn(Self::Bar<'a, T>)>(t: T, f: FN){
f(&t);
}
}
But it does not work out:
error[E0311]: the parameter type `T` may not live long enough
--> src/lib.rs:10:8
|
10 | fn foo<T, FN: for<'a> Fn(Self::Bar<'a, T>)>(t: T, f: FN){
| ^^^ ...so that the type `T` will meet its required lifetime bounds
|
help: consider adding an explicit lifetime bound...
|
10 | fn foo<'a, T: 'a, FN: for<'a> Fn(Self::Bar<'a, T>)>(t: T, f: FN){
| +++ ++++
error: could not compile `playground` due to previous error
I am quite sure the issue is I can't bound T: 'a
in the generic parameter list of foo
while keeping 'a
as a HRTB.
My approach to find the solution led me to this function:
fn foo<T, FN: Fn(&T)>(t: T, f: FN){
f(&t);
}
And trying to desugar it to the point where I can see how the lifetimes and bounds to T
work. But I only got so far which yet lacks bounds to T
:
fn foo<T, FN: for<'a> Fn(&'a T)>(t: T, f: FN){
f(&t);
}
I know T
is not bounded, but I need to be able to prove that to the compiler with my trait, like this function here is be able to.
What could I do here?
I attempted to take T
by reference (&mut T
because Foo::Bar
might require that in another impl) but all ways I got it compile made me deal with the very same error at the calling site.