Rust Iron::new()::http()截获stdin

Rust Iron::new()::http()截获stdin,rust,iron,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"); prin

我正在尝试使用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!")))
}
为此:

let listener = Iron::new(hello_world).http("localhost:3000").unwrap();
我收到了您输入的字符串:我的控制台上的一些文本。所以它似乎起作用了。但现在我有关于未使用变量的警告。这种行为令人困惑


有人能解释为什么会发生这种情况吗?

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

  • Iron::new(hello_world).http(“localhost:3000”).unwrap()
    生成一个类型为
    侦听的对象,该对象将开始在单独的线程中侦听http请求
  • Listening
    结构实现了
    Drop
    特性,即
    Listening
    类型的任何对象在超出范围时都将运行
    Drop
    函数。所述drop函数将加入侦听线程,阻止程序的进一步执行
  • 通过不将
    侦听
    对象分配给变量,它会立即超出范围。这意味着在对象创建后立即运行
    drop
    功能
  • 代码中的替代解释 程序的第一个版本:

    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
    }
    

    因为当您删除侦听器时,它将阻塞直到服务器死亡,当您将其移动到变量时,它将在删除变量时阻塞(即作用域结束)——您可以在变量前面加上
    \u
    (如
    \u listener
    )以消除未使用的警告。谢谢。感谢你用
    \u listener
    进行了出色的破解。我不知道。谢谢你的详细解释!这个图案在锈迹中有名字吗?我的意思是,这是一种常见的做法吗?这是一种常见的图案,不仅仅在锈迹中。C++具有析构函数,例如,当对象超出范围时也执行析构函数。您可以在中阅读更多关于
    Drop
    ,该模式在没有垃圾收集的语言中非常有用,如Rust。您可以使用它来确保在销毁对象时释放对象分配的任何内存(否则您将不得不手动执行此操作,有可能忘记执行此操作并导致内存泄漏)。这种模式在C++中被调用,并且我在RIST上下文中看到了相同的名称(例如,参见)
    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
    }