Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
920 views
in Technique[技术] by (71.8m points)

rust - How to check for EOF with `read_line()`?

Given the code below, how can I specifically check for EOF? Or rather, how can I distinguish between "there's nothing here" and "it exploded"?

match io::stdin().read_line() {
    Ok(l) => print!("{}", l),
    Err(_) => do_something_else(),
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the 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.

This means we can check for a successful value of zero:

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(())
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...