我在理解为什么可以编写像
这样的代码时遇到了问题extern crate futures;
extern crate hyper;
use hyper::server::{Http, Request, Response, Service};
struct Environment {}
struct HttpService<'a> {
pub env: &'a Environment,
}
impl<'a> Service for HttpService<'a> {
type Request = Request;
type Response = Response;
type Future = futures::future::FutureResult<Self::Response, Self::Error>;
type Error = hyper::Error;
fn call(&self, _req: Request) -> Self::Future {
futures::future::ok(Response::new())
}
}
fn foo() {
let addr = "127.0.0.1:3000".parse().unwrap();
let env = Environment {};
// <<<<< why is the non-static &env accepted here?
let server = Http::new().bind(&addr, move || Ok(HttpService { env: &env }));
server.unwrap().run().unwrap();
}
bind()
方法为defined
fn bind<S, Bd>(&self, addr: &SocketAddr, new_service: S) -> Result<Server<S, Bd>>
where
S: NewService<Request = Request, Response = Response<Bd>, Error = Error> + 'static,
Bd: Stream<Item = B, Error = Error>,
这意味着闭包的生命周期必须'static
,并且传递&env
会违反。
为什么它适用于上面的代码,而不是
fn bar() {
use tokio_core::net::TcpListener;
let addr = "127.0.0.1:3000".parse().unwrap();
let env = Environment {};
let mut core = tokio_core::reactor::Core::new().unwrap();
let handle = core.handle();
use futures::Stream;
use futures::Future;
let listener = TcpListener::bind(&addr, &handle)
.unwrap()
.incoming()
.for_each(move |(socket, addr)| {
let svc = HttpService { env: &env };
let fut = Http::<hyper::Chunk>::new()
.serve_connection(socket, svc)
.map(|_| ())
.map_err(|_| panic!("err"));
handle.spawn(fut);
Ok(())
});
}
与预期的与生命周期相关的错误失败:
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> src/main.rs:50:42
|
50 | let svc = HttpService { env: &env };
| ^^^^
|
note: first, the lifetime cannot outlive the lifetime as defined on the body at 49:19...
--> src/main.rs:49:19
|
49 | .for_each(move |(socket, addr)| {
| ___________________^
50 | | let svc = HttpService { env: &env };
51 | | let fut = Http::<hyper::Chunk>::new()
52 | | .serve_connection(socket, svc)
... |
56 | | Ok(())
57 | | });
| |_________^
note: ...so that closure can access `env`
--> src/main.rs:50:42
|
50 | let svc = HttpService { env: &env };
| ^^^^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `HttpService<'_>` will meet its required lifetime bounds
--> src/main.rs:53:18
|
53 | .map(|_| ())
| ^^^
更好的是,如何使用更强大的Http::serve_*()
函数编写后一部分?
我正在使用
答案 0 :(得分:3)
通过使用move
关键字,您已将Environment
变量的所有权转让给了关闭。这意味着闭包本身没有引用,因此不会涉及生命周期。闭包的 return 值具有与闭包本身相关的生命周期,但允许这样做。
请注意,此案例使用NewService
。
在Tokio示例中,您调用Handle::spawn
,这需要'static
生命周期。未来参考Environment
,但不符合该要求。
请注意,此案例使用Service
。