#Writing a trait that is generic over lifetimes

43 messages · Page 1 of 1 (latest)

heavy flax
#

Ah, empty threads

wispy wadi
#

i am sorry. i realized my question is not fleshed out last min

slightly related question: if I have an associated type, is there a way to constrain that type by its lifetime?

I want this:

trait RequestHandler {
type Response: 'self;
fn get_response(&self) -> Self::Response;
}

but of course self doesn't exist

I can't make get_response return &Self::Response, it may be a static struct or a smart pointer with a lifetime

heavy flax
#

I think this takes GATs.

wispy wadi
#

yeah. i can't find an equiv stdlib api which makes me wonder

heavy flax
#
trait RequestHandler {
  type Response<'this>;
  fn get_response<'this>(&'this self) -> Self::Response<'this>
}
#

I think you can elide the lifetime params on the function, but I'd at least keep Self::Response<'_>

wispy wadi
#

that's GAT, right?

heavy flax
#

Yup

wispy wadi
#

wait GAT are stable?

heavy flax
#

They're close, but I don't think they're stable yet?

wispy wadi
#

if I changed the trait to work like trait RequestHandler<Response> I think that doesn't buy me anything, right?

#

then it's just HKT or something else

heavy flax
#

Then you'd need

trait RequestHandler<Response<'_>> {
  fn get_response<'this>(&'this self) -> Response<'this>
}
```which is indeed a HKT
#

(HKTs are basically type theory speak for generic generics)

wispy wadi
#

yeah

light briar
#

yeah I just realized...

#

the trait needs a lifetime then trait RequestHandler<'resp, Response<'resp>>

#

you can do it with an associated type too

#

I'm slightly confused

heavy flax
#

Oh yeah, if you give the trait a lifetime

#

No wait, not even then

heavy flax
#

You're giving a generic parameter its own generic parameter

light briar
#

ah no

#

right

heavy flax
#

Maybe Response: 'resp?

light briar
#

I confused impl with declaration

#

Response was a struct in my head

heavy flax
#

Ah, I see

light briar
#

anyway, rs trait RequestHandler<'resp> { type Response: 'resp; fn get_response(&'resp self) -> Self::Response } should definitely (maybe) be possible

#

if it's not, I'm going crazy

heavy flax
#

This is possible, yes. It's slightly weaker than GATs, but it might suffice

light briar
#

or just use nougat ferrisBigBrain

#

once it's ready

wispy wadi
#

i already tried giving the trait a lifetime

#

i didn't even grok why that didn't work

light briar
#

well, it usually works

#

but is less ergonomic to use than GATs

wispy wadi
#

if you have a impl<'a> RequestHandler<'a> for Foo, how do you constrain 'a

#

hmm wait

#

yeah okay that worked actually, it just caused a lot of problems down the line