2016-08-12 100 views
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)); 

回答

4

的錯誤信息是這裏幾乎是不可理解編譯(有一個issue爲它!)。

問題是沒有推斷閉包的類型。我們可以幫助編譯器註釋的request類型:我改變了context類型&Context

extern crate iron; 
extern crate router; 

use iron::prelude::*; 
use router::Router; 
use std::collections::HashMap; 
use std::sync::{Arc, Mutex}; 

#[derive(Clone, Default)] 
struct Context { 
    cache: Arc<Mutex<HashMap<String, String>>>, 
} 

fn main() { 
    let context = Context::default(); 
    let mut router = Router::new(); 

    let c = context.clone(); 
    router.get("/", move |request: &mut Request| index(request, &c), "index"); 

    Iron::new(router).http("localhost:80").unwrap(); 
} 

fn index(_: &mut Request, context: &Context) -> IronResult<Response> { 
    Ok(Response::with((iron::status::Ok, "index"))) 
} 

注(否則,封閉只會implementsFnOnce),並使用move(關閉必須'static一生來實現Handler)。

爲了能夠在index中更改cache,您需要將change的類型設置爲Arc<Mutex<HashMap<String, String>>>或類似的。

+0

非常感謝。現在我沒有在我的原始問題中說明這一點,但我有不止一個這樣的router.get-lines(這是使用路由器的一點)並添加第二行那樣(router.get(「/ hi」 ,move | ... | hi(...));)會導致新的編譯器錯誤。錯誤:移動值的捕獲:'上下文' – Nozdrum

+0

@Nozdrum查看更新。 – malbarbo

+0

再次非常感謝。這裏有很多我不明白的地方(爲什麼我需要克隆所有東西,當結構的內容是相同的,爲什麼我需要'移動'我的閉包,這甚至意味着什麼,爲什麼這些派生在我的結構)。我閱讀了防火牆編程的書籍/文檔,現在才意識到我並不真正瞭解他們在那裏寫了什麼。 – Nozdrum

相關問題