rust - 如何使用 `read_line()` 检查 EOF?

标签 rust

给出下面的代码,我如何专门检查 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/

相关文章:

build - 使用 Cargo 进行源代码构建(外部构建目录)?

rust - 通过 32 位整数索引向量

pointers - 指向 Result<Vec<f64>, _> 中向量第一个元素的指针已损坏

generics - 通用特征对象的向量

rust - 将 `use` 声明放入 Rust 的推荐位置在哪里?

linux - 从 64 位 arch linux 为树莓派 `armv7-unknown-linux-gnueabihf` 编译 Rust 程序

path - 从 Rust 中的给定路径中惯用地提取文件扩展名

Rust future -- 将两个 future 结合在一起

rust - 如何通过serde中的内部字段将 `Option`设置为None?

list - 向前和向后迭代