Skip to content

Instantly share code, notes, and snippets.

@polybuildr polybuildr/Cargo.toml

Last active Dec 6, 2019
Embed
What would you like to do?
Rust error message "captured variable cannot escape `FnMut` closure body"
[package]
name = "test"
version = "0.1.0"
authors = ["Foo Bar <foobar@example.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
hyper = "0.12"
futures = "0.1"
error: captured variable cannot escape `FnMut` closure body
--> src/main.rs:18:13
|
18 | / match (req.method(), req.uri().path()) {
19 | | (&Method::POST, "/foo") => {
20 | | // let data_map = Arc::clone(&data_map);
21 | | let response_future =
... |
36 | | )),
37 | | }
| |_____________^ returns a reference to a captured variable which escapes the closure body
|
= note: `FnMut` closures only have access to their captured variables while they are executing...
= note: ...therefore, they cannot allow references to captured variables to escape
error: aborting due to previous error
error: could not compile `test`.
To learn more, run the command again with --verbose.
use futures::{future, Stream};
use hyper::rt::{self, Future};
use hyper::service::service_fn;
use hyper::{Body, Chunk, Error, Method, Request, Response, Server};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
type ResponseFuture = Box<dyn Future<Item = Response<Body>, Error = Error> + Send>;
fn main() {
let addr = ([127, 0, 0, 1], 3000).into();
let data_map = Arc::new(Mutex::new(HashMap::new()));
let service = move || {
let data_map = Arc::clone(&data_map);
service_fn(move |req: Request<Body>| -> ResponseFuture {
match (req.method(), req.uri().path()) {
(&Method::POST, "/foo") => {
// let data_map = Arc::clone(&data_map);
let response_future =
req.into_body().concat2().and_then(/* move */ |_body: Chunk| {
data_map
.lock()
.unwrap()
.insert("hello".to_string(), "world".to_string());
future::ok(Response::new(Body::from("ok")))
});
Box::new(response_future)
}
_ => Box::new(future::ok(
Response::builder()
.status(404)
.body(Body::from(""))
.unwrap(),
)),
}
})
};
let server = Server::bind(&addr)
.serve(service)
.map_err(|e| eprintln!("server error: {}", e));
rt::run(server);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.