Can't capture dynamic environment in a fn item about iron lib

#1

Hello, I use the cassandra of the c/c++ driver to query, and then return the data.
Therefore, both cass (LinkedList) and cass_it (Vec) can show the result of the query.
However, I want to display the results to the web using the json format, so I chose to reassemble the data using vec. However, there is a problem:

error[E0434]: can't capture dynamic environment in a fn item
   --> src/main.rs:306:42
    |
306 |         let out = serde_json::to_string(&cass_it).unwrap();
    |                                          ^^^^^^^
    |
    = help: use the `|| { ... }` closure form instead

What is wrong? format issue?

Code:

fn main() {

    let mut cass = unsafe{cass_connect()};
    let mut cass_it = Vec::new();

    for cc in cass.iter() {
        cass_it.push(cc);
    }

    println!("{:?}", cass_it);

    let mut router = Router::new();
    let localhost = "localhost:3009".to_string();

    fn handler(req: &mut Request) -> IronResult<Response> {


        // convert the response struct to JSON
        let out = serde_json::to_string(&cass_it).unwrap();

        let content_type = "application/json".parse::<Mime>().unwrap();

        Ok(Response::with((content_type, status::Ok, out)))
    }

    router.get("/", handler, "index");

    info!("Listening on {}", localhost);
    Iron::new(router).http(localhost).unwrap();

}

Complete code

#2

fn handler is forbidden from accessing any local variables from outside of that function. It can only use global variables or its arguments. You can’t define cass_it outside the fn and use it inside.

Only closures can have context. Try let handler = |…| …

#3
1 Like
#4

But now there is another problem:

error[E0373]: closure may outlive the current function, but it borrows `cass`, which is owned by the current function
    --> src/main.rs:360:19
     |
360 | let handler = |req: &mut Request| {
     | ^^^^^^^^^^^^^^^^^^^ may outlive borrowed value `cass`
361 | // convert the response struct to JSON
362 | let out = serde_json::to_string(&cass).unwrap();
     | ---- `cass` is borrowed here
     |
Note: function requires argument type to outlive `'static`
    --> src/main.rs:367:5
     |
367 | router.get("/", handler, "index");
     | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Help: to force the closure to take ownership of `cass` (and any other referenced variables), use the `move` keyword
     |
360 | let handler = move |req: &mut Request| {
     | ^^^^^^^^^^^^^^^^^^^^^^^^^

why need use the ‘static’? about lifetime?
P.S.(Because i change return type, so just use “cass”, remove “cass_it” already)

#5

Maybe some details didn’t notice, and, unconsciously, it can be executed on the web. However, I believe that more tests are needed. This is my git.Currently executable code.
Thank for help!!