#Writing a trait that is generic over lifetimes
43 messages · Page 1 of 1 (latest)
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
I think this takes GATs.
yeah. i can't find an equiv stdlib api which makes me wonder
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<'_>
that's GAT, right?
Yup
wait GAT are stable?
They're close, but I don't think they're stable yet?
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
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)
yeah
it's possible to have rs trait RequestHandler<Response<'resp>> { fn get_response(&'resp self) -> Response<'resp> } and you can use for<'a> RequestHandler<Response<'a>> and stuff
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
Wait, since when is that allowed
Oh yeah, if you give the trait a lifetime
No wait, not even then
I don't think that's legal.
You're giving a generic parameter its own generic parameter
Maybe Response: 'resp?
Ah, I see
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
This is possible, yes. It's slightly weaker than GATs, but it might suffice
