[SOLVED] Using struct members within a closure

With the following code:

extern crate iron;

use iron::{
    prelude::*,
    status,
    Iron
};

struct Handler;

impl Handler {

    fn handle(&self) -> String {
        "Something".to_string()
    }
}

struct WebServer {
    handler: Handler
}

impl WebServer {

    fn new() -> Self {
        WebServer {
            handler: Handler {}
        }
    }

    fn listen(&self) {
        Iron::new(|req: &mut Request| {
            Ok(Response::with((status::Ok, self.handler.handle())))
        }).http("localhost:5000").unwrap();
    }
}

fn main() {
    let server = WebServer::new();
    server.listen();
}

I get the following errors

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/main.rs:32:19
   |
32 |           Iron::new(|req: &mut Request| {
   |  ___________________^
33 | |             Ok(Response::with((status::Ok, self.handler.handle())))
34 | |         }).http("localhost:5000").unwrap();
   | |_________^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 31:5...
  --> src/main.rs:31:5
   |
31 | /     fn listen(&self) {
32 | |         Iron::new(|req: &mut Request| {
33 | |             Ok(Response::with((status::Ok, self.handler.handle())))
34 | |         }).http("localhost:5000").unwrap();
35 | |     }
   | |_____^
   = note: ...so that the types are compatible:
           expected &&WebServer
              found &&WebServer
   = note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@src/main.rs:32:19: 34:10 self:&&WebServer]` will meet its required lifetime bounds
  --> src/main.rs:32:9
   |
32 |         Iron::new(|req: &mut Request| {
   |         ^^^^^^^^^

error: aborting due to previous error

I'm trying to access a struct member from within a Closure, but I'm unsure how to resolve these lifetime errors.

Is there a reason you’re storing the handler in a field?

But let’s assume that was convenient, you likely want:

fn listen(self) {
       // move `handler` out of self
       let handler = self.handler;
        // move it into the closure - the closure
        // now owns it
        Iron::new(move |req: &mut Request| {
            Ok(Response::with((status::Ok, handler.handle())))
        }).http("localhost:5000").unwrap();
    }

It's being stored in the field as there's stateful information stored within the Handler struct. However, your solution works, thanks! :tada: