Given this trait from another crate:
trait ToMut<'a> {
type Output;
fn to_mut(&'a mut self) -> Self::Output;
}
I'd like to use it in my generic function as an intermediate step, but it's result wont leave function. So whatever lifetime I provide should be "contained" within the function, is it possible?
I start from:
struct P<T>(T);
fn init<I,A,B>(mut t: I) -> I
where I: ToMut<Output = P<A>>,
A: DerefMut<Target = B>,
B: Default
{
let mut f = t.to_mut();
*f.0 = Default::default();
t
}
Which fails to compile because lifetime is not provided. There are 2 options I can think of to provide one:
-
fn init<I,A,B>(mut t: I) -> I where for<'a> I: ToMut<'a, Output = P<A>>
which results in the
implementation of
ToMutis not general enough
error. Reading about it kinda make sense, in the generic bounds we ask to ToMut for any lifetime, but our implementation can do only for one concrete lifetime. -
Add generic lifetime parameter:
fn init<'a, I,A,B>(mut t: I) -> I where I: ToMut<'a, Output = P<A>> + 'a,
but then lifetime is set externally by the caller and obviosly can't be satisfied by the internal
to_mut()
call which result is discarded within the function.
How can I use ToMut
trait in my function?
Full example: Rust Playground