3
我想有一个在所有处理程序中都可用的上下文结构,但我无法通过编译器。我怎样才能传递处理程序之间的变量
举一个例子,我想是这样的
extern crate iron;
extern crate router;
use iron::prelude::*;
use router::Router;
use std::collections::HashMap;
struct Context {
cache: HashMap<String, String>,
}
fn main() {
let mut context = Context { cache: HashMap::new(), };
let mut router = Router::new();
router.get("/", |request| index(request, context));
Iron::new(router).http("localhost:80").unwrap();
}
fn index(_: &mut Request, context: Context) -> IronResult<Response> {
Ok(Response::with((iron::status::Ok, "index")))
}
这不会有冗长的错误信息
error: type mismatch resolving `for<'r, 'r, 'r> <[[email protected]\main.rs:... context:_] as std::ops::FnOnce<(&'r mut iron::Request<'r, 'r>,)>>::Output == std::result::Result<iron::Response, iron::IronError>`:
expected bound lifetime parameter ,
found concrete lifetime [E0271]
src\main.rs:... router.get("/", |request| index(request, context));
非常感谢。现在我没有在我的原始问题中说明这一点,但我有不止一个这样的router.get-lines(这是使用路由器的一点)并添加第二行那样(router.get(“/ hi” ,move | ... | hi(...));)会导致新的编译器错误。错误:移动值的捕获:'上下文' – Nozdrum
@Nozdrum查看更新。 – malbarbo
再次非常感谢。这里有很多我不明白的地方(为什么我需要克隆所有东西,当结构的内容是相同的,为什么我需要'移动'我的闭包,这甚至意味着什么,为什么这些派生在我的结构)。我阅读了防火墙编程的书籍/文档,现在才意识到我并不真正了解他们在那里写了什么。 – Nozdrum