I am getting a lifetime error from a T that is owned by the current function and not a reference

here is my code

pub struct JsonRespWithCookie<T: Serialize>(pub Result<T, Err>);
impl<T: Serialize> Responder for JsonRespWithCookie<T> {
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<HttpResponse, Self::Error>>>>;
    fn respond_to(self, req: &HttpRequest) -> Self::Future {
        let cookie = req.cookie("token");
        let store: Option<Data<Store>> = req.app_data().cloned();
        Box::pin(async move {
            if let Err(e) = self.0 {
                return Err(res!(e, e));
            let store =
                store.ok_or(res!(e, Err::Unknown("no app data in the responder".into())))?;
            let mut cookie = cookie.ok_or(res!(e, Err::InvalidCreds))?.value().to_owned();
            let creds = check_token(store.clone(), cookie).await.map_err(res!(e))?;
            if creds.exp
                > chrono::Utc::now().timestamp() - chrono::Duration::minutes(30).num_seconds()
                cookie = extend_token(store, creds).await.map_err(res!(e))?;
                .cookie(Cookie::new("token", cookie))

I dont understand why T must have a lifetime since it is not a reference
and here is the error

Could you please provide the error?

I have updated the post with the error details

1 Like

The box you've defined:

type Future = Pin<Box<dyn Future<Output = Result<HttpResponse, Self::Error>>>>;

Is implicitly

type Future = Pin<Box<dyn Future<Output = Result<HttpResponse, Self::Error>> + 'static>>;

So, when you're dealing with T, it must be T: 'static, meaning it contains no fields with lifetimes which aren't 'static.


It's worth noting that T is a generic type, and you've not limited that at all. Sure, a concrete struct like String is a type, but so is &String or &u32. T could very well be &u32, with some lifetime which isn't 'static. Specifically, it can be a reference, because you haven't told the compiler you don't want that.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.