I have two generic parameters, and need to specify that one outlives the other. Is this possible?
To start at the beginning, I have trait implementations like these (source):
impl<H: DrawHandle> DrawHandle for Box<H> {...}
impl<S> DrawHandle for stack_dst::ValueA<dyn DrawHandle, S>
where
S: Default + Copy + AsRef<[usize]> + AsMut<[usize]>,
{...}
and wish to replace them with a single, generic impl. At first glance, the following works:
impl<D: DrawHandle + ?Sized, T: DerefMut<Target = D>> DrawHandle for T {...}
but, it stumbles on one of the methods due to a returned reference:
error[E0311]: the parameter type `D` may not live long enough
--> src/draw/handle.rs:444:9
|
444 | self.deref_mut().draw_device()
| ^^^^^^^^^^^^^^^^
|
note: the parameter type `D` must be valid for the anonymous lifetime #1 defined on the method body at 443:5...
--> src/draw/handle.rs:443:5
|
443 | / fn draw_device(&mut self) -> (Pass, Coord, &mut dyn Draw) {
444 | | self.deref_mut().draw_device()
445 | | }
| |_____^
note: ...so that the type `D` is not borrowed for too long
--> src/draw/handle.rs:444:9
|
444 | self.deref_mut().draw_device()
| ^^^^^^^^^^^^^^^^
I can probably revise this method to take a closure instead of returning a reference, but I'd prefer not to. This means I need to prove that the type D
outlives the self
parameter of draw_device
. This would be easy... but lifetime bounds on trait-method impls must match those on the trait, and on the trait there is no equivalent D
to place this lifetime restriction on. It makes more sense then to observe that T
must outlive the self
parameter, and therefore require that D
outlives T
on the trait implementation, hence my question.
At first stab, I could try this, but it fails (since 'b
can be arbitrarily short):
impl<'a, 'b, D: DrawHandle + ?Sized + 'a, T: DerefMut<Target = D> + 'b> DrawHandle for T where 'a: 'b {...}
I think it is currently not possible to do this?