0

I am trying to implement an HTTP request handler using Actix-Web. Here is the relevant part of my code:

impl<S> Handler<S> for FooBarHandler {
    type Result = Box<Future<Item = HttpResponse, Error = Error>>;

    fn handle(&mut self, req : HttpRequest<S>) -> Self::Result {
        req.json().from_err().and_then(|foo : Foo|
            self.baz.qux(foo);
            Ok(HttpResponse::Ok().finish())
        }).responder()
    }
}

However, I receive this error message:

error[E0477]: the type  `mymod::futures::AndThen<mymod::futures::future::FromErr<mymod::actix_web::dev::JsonBody<mymod::actix_web::HttpRequest<S>, mymod::Foo>, mymod::actix_web::Error>, std::result::Result<mymod::actix_web::HttpResponse, mymod::actix_web::Error>, [closure@src/mymod.rs:53:40: 56:10 self:&&mut mymod::FooBarHandler]>` does not fulfill the required lifetime
  --> src/mymod.rs:56:12
   |
56 |         }).responder()
   |            ^^^^^^^^^
   |
   = note: type must satisfy the static lifetime

I do not understand this error message at all. The code is practically identical to this example, which does not contain any lifetime annotations.

Alex
  • 699
  • 1
  • 10
  • 20
  • As currently posed, this question is off-topic: *Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and **the shortest code necessary to reproduce it in the question itself**.*. You haven't provided the definition of `FooBarHandler`, you haven't shown what crates (and their versions!) you are importing, etc. In fact, your code **isn't syntactically valid**. – Shepmaster May 04 '18 at 18:04

1 Answers1

2

You use self inside your .and_then future, which violates lifetime requirement.

Nikolay Kim
  • 144
  • 1
  • How should I avoid this? I tried adding `let baz = self.baz.clone();` before the `and_then` future, and then replacing `self.baz` with `baz`, but that gave the following error: `error[E0373]: closure may outlive the current function, but it borrows `baz`, which is owned by the current function` – Alex May 04 '18 at 01:39
  • 1
    Do clone and then move it to the closure, `.and_then(move |..| {...})` – Nikolay Kim May 04 '18 at 01:47
  • I tried that, but I get these errors: `The parameter type 'S' may not live long enough`. The compiler suggests adding an explicit lifetime bound- `S : 'static`, but that results in errors about the trait not being able to be shared between threads safely. – Alex May 04 '18 at 01:53