Is it even possible to implement `Deref` that dereferences to a type with a lifetime?

I have a situation that looks something like this:

#[derive(yoke::Yokeable)]
pub struct Parsed<'a> {
    // ..
}

pub struct Owned {
    inner: yoke::Yoke<Parsed<'static>, Arc<[u8]>>,
}

impl Deref for Owned {
    type Target = Parsed<?>;

    fn deref(&self) -> &Self::Target {
        self.inner.get()
    }
}

For those who are not familiar, yoke allows to create self-referential data structures. In this case parsing is a non-negligible operation, so I'm storing the results in the data structure alongside the buffer it was parsed from.

<?> is the problem here. I tried to use for<'a> Parsed<'a>, but compiler doesn't seem to understand this syntax in that position. The lifetime is the same as &self, but I wasn't able to find a way to express this in a way that compiler understands.

It is possible to do at on nightly or did I hit the corner that is not implementable today?
I'd be much more ergonomic to have this kind of Deref implemented (for now I have an explicit method for this purpose).

The lifetime relationship you want cannot be expressed given the definition of the Deref trait. <Owned as Deref>::Target has to be a single type and cannot vary depending on the input lifetime.

If Deref were defined with a generic associated type (GAT),

trait Deref {
    type Target<'a>;
    fn deref<'a>(&'a self) -> &'a Self::Target<'a>;
} 

or even

trait Deref {
    type Target<'a>;
    fn deref<'a>(&'a self) -> Self::Target<'a>;
} 

then this would be possible, but it is not (and couldn’t have been, because GATs didn’t exist in Rust 1.0).

1 Like

Do you know what is the path forward for this that I can follow, maybe an upstream issue or some discussion?

I bet this has been discussed extensively already.

No, I rather expect this is infeasible to change. Here’s a prior discussion:

It comes up from time to time (see e.g. this brief discussion). The main issues are backward compatibility and avoiding exponential blowup if you allow the targets of Deref and DerefMut to be different.