Iron :: new():: http()拦截stdin

时间:2017-04-09 19:28:52

标签: rust iron

我正在尝试使用Rust和Iron实现教育客户端 - 服务器应用程序。我遇到了我无法理解的行为。这是代码:

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 个答案:

答案 0 :(得分:2)

在代码的第一个版本中,第一行将阻止等待传入连接。这是因为以下原因:

  1. Iron::new(hello_world).http("localhost:3000").unwrap()生成Listening类型的对象,该对象将开始在单独的线程中侦听http请求
  2. Listening结构实现了Drop特征,即Listening类型的任何对象在超出范围时将运行drop函数。所述丢弃功能将加入监听线程,阻止进一步执行您的程序
  3. 如果不将Listening对象分配给变量,则会立即超出范围。这意味着 drop函数在对象创建后立即运行
  4. 代码中的替代解释

    您的计划的第一个版本:

    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)
    }
    

    引入变量的结果:

    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
    }