为什么这个示例铁代码似乎阻止了?

时间:2015-08-11 06:39:24

标签: rust iron

我正在运行http://ironframework.io主页中的这个hello world示例代码:

extern crate iron;

use iron::prelude::*;
use iron::status;

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

    Iron::new(hello_world).http("localhost:3000").unwrap();
    println!("On 3000");
}

我希望在标准输出上看到“On 3000”,但它永远不会出现。我的猜测是主线程在执行println之前被阻塞了。为什么会这样?

如果我使用临时函数并在之后调用unwrap,我会得到预期的输出:

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

    let result = Iron::new(hello_world).http("localhost:3000");
    println!("On 3000");
    result.unwrap();
}

为什么在返回值上调用unwrap时行为会发生变化?

我正在运行铁锈1.1.0和铁0.1.20。

1 个答案:

答案 0 :(得分:3)

在我写完问题之后,答案就出现了。

http函数返回HttpResult<Listening> Listening类型有一个析构函数,它在一个线程上调用join,阻塞。

在第一种情况下,返回对象的生命周期在解包调用之后完成,因此析构函数被调用并加入线程。如果我将它分配给变量,则在调用unwrap之前不会调用析构函数。