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