哪个条件会在“ read_line”中触发错误处理,然后“ expect”?

问题描述 投票:1回答:1

[使用read_line()读取输入流时,如果不使用.expect()跟随语句,则编译器将警告您this `Result` may be an `Err` variant, which should be handled

我想了解的是哪种情况将触发此类错误处理。

我已经尝试将程序管道传输到另一个程序(./my_program | echo "hello"),所以我将没有机会输入任何输入,并且应该能够看到实际的错误处理。令我惊讶的是,它实际上导致了恐慌状态:

thread 'main' panicked at 'failed printing to stdout: Broken pipe (os error 32)', src/libstd/io/stdio.rs:792:9

在本书The Rust Programming Language的这段代码中,我们指定了一个字符串,我相信当程序无法读取输入流时,应该打印该字符串:

use std::io;

fn main() {
    println!("Guess the number!");

    println!("Please input your guess.");

    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .expect("Failed to read line");

    println!("You guessed: {}", guess);
}

我如何真正看到该行为在起作用?

rust
1个回答
4
投票

让我们关注消息来源:

让我们尝试一下:

append_to_string function
© www.soinside.com 2019 - 2024. All rights reserved.