给出下面的代码,我如何专门检查 EOF?或者更确切地说,我如何区分“这里什么都没有”和“它爆炸了”?
match io::stdin().read_line() {
Ok(l) => print!("{}", l),
Err(_) => do_something_else(),
}
最佳答案
来自documentation for read_line
:
If successful, this function will return the total number of bytes read.
If this function returns
Ok(0)
, the stream has reached EOF.
这意味着我们可以检查成功的零值:
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let mut empty: &[u8] = &[];
let mut buffer = String::new();
let bytes = empty.read_line(&mut buffer)?;
if bytes == 0 {
println!("EOF reached");
}
Ok(())
}
关于rust - 如何使用 `read_line()` 检查 EOF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27475113/