[使用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);
}
我如何真正看到该行为在起作用?
让我们关注消息来源:
std::io::Stdin::read_line
委托给std::io::Stdin::read_line
。std::io::StdinLock::read_line
委托给私人std::io::StdinLock::read_line
。std::io::StdinLock::read_line
在非UTF-8输入上返回错误。让我们尝试一下:
append_to_string
function