I have following foreign trait I don't control:
pub trait Foo<T> {
fn foo(input: &T) -> Self;
}
I want to implement that trait for a reference of an unsized Type that lives inside T
impl Foo<Bar> for &[String] {
fn from_ref(input: &Bar) -> Self {
&input.bar
}
}
The problem is that this does not compile. It requires input to outlive the returned value. Which is the case because it stores it.
I tried adding explicit lifetimes but apparently I can't add a lifetime to input&Bar because of function signature. I also can't restrict the implicit lifetime '_ in the where clause.
You cannot implement what you want. The trait interface does not define a lifetime relationship between input
and Self
. So an implementation cannot establish one.
In order to do that, the trait would either need:
a lifetime defined on it and linked to the reference:
pub trait Foo<'a, T> {
fn foo(input: &'a T) -> Self;
}
to use a generic associated type:
pub trait Foo<T> {
type Ref<'a> where T: 'a;
fn foo<'a>(input: &'a T) -> Self::Ref<'a>;
}