2017-04-09 83 views
2

我試圖使用Rust和Iron實現教育客戶端 - 服務器應用程序。我遇到了我無法理解的行爲。下面是代碼:Iron :: new():: http()攔截stdin

fn main() { 
    Iron::new(hello_world).http("localhost:3000").unwrap(); 

    let mut input = String::new(); 
    io::stdin().read_line(&mut input) 
     .expect("Failed to read line"); 

    println!("You entered: {}", &input) 
} 


fn hello_world(_: &mut Request) -> IronResult<Response> { 
    Ok(Response::with((status::Ok, "Hello World!"))) 
} 

當我運行它,並嘗試從鍵盤輸入的東西,行您輸入:某些文本沒有出現。

但之後我改變了這一行:

Iron::new(hello_world).http("localhost:3000").unwrap(); 

有了這個:

let listener = Iron::new(hello_world).http("localhost:3000").unwrap(); 

你進入我得到的字符串:我的控制檯上的一些文字。所以它似乎工作。但是現在我有關於未使用的變量的警告。這種行爲令人困惑。

任何人都可以解釋爲什麼這實際上發生?

+1

因爲當你把聽者它會阻止:

fn main() { Iron::new(hello_world).http("localhost:3000").unwrap(); // The listening thread is joined here, so the program blocks // The instructions below will never be executed let mut input = String::new(); io::stdin().read_line(&mut input) .expect("Failed to read line"); println!("You entered: {}", &input) } 

引入變量的結果直到服務器死亡,當你將它移動到一個變量時,它會在變量被丟棄時(即作用域結束)阻塞 - 你可以用'_'(l ike'_listener')沉默未使用的警告。 –

+0

謝謝。並感謝'_listener'的精彩入侵。我不知道這件事。 –

回答

2

在您的代碼的第一個版本中,第一行將阻止等待傳入連接。這是因爲以下的原因:

  1. Iron::new(hello_world).http("localhost:3000").unwrap()產生Listening類型的對象,這將開始收聽到http在單獨的線程請求
  2. Listening結構實現Drop特性,即Listening類型的任何對象在超出範圍時都會運行drop函數。所說的drop功能將加入監聽線程,阻止你的程序的進一步執行。
  3. 通過不將Listening對象分配給變量,它立即超出範圍。這意味着drop函數在對象創建後立即運行
代碼

另一種解釋

程序的第一個版本:

fn main() { 
    let listener = Iron::new(hello_world).http("localhost:3000").unwrap(); 

    let mut input = String::new(); 
    io::stdin().read_line(&mut input) 
     .expect("Failed to read line"); 

    println!("You entered: {}", &input) 

    // The listening thread is joined here, so the program blocks 
    // As you can see, the program will not exit 
} 
+0

感謝您的詳細解釋!這個模式在Rust裏有一個名字嗎? –

+0

我的意思是,這是否是一種常見做法? –

+0

這是一種常見的模式,不僅在Rust中。例如,C++具有析構函數,當對象超出範圍時也會執行這些析構函數。您可以在[Rust Book](https://doc.rust-lang.org/nightly/book/first-edition/drop.html)中閱讀關於Drop的更多信息 – aochagavia