rusttraitsreference-lifetimes

Implement foreign Trait with Implicit lifetime on method


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.


Solution

  • 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: