read_line

Function read_line 

Source
pub fn read_line<R: Read>(reader: R) -> Result<String>
Expand description

Read a line from a reader into a new String.

This is a convenience function for BufRead::read_line. Using this function avoids having to create a variable first and provides more type safety since you can only get the buffer out if there were no errors. (If you use BufRead::read_line you have to remember to check whether the read succeeded because otherwise your buffer will be empty or only partially full.)

§Performance

The downside of this function’s increased ease of use and type safety is that it gives you less control over performance. For example, you can’t pre-allocate memory like you can using String::with_capacity and Read::read_to_string. Also, you can’t re-use the buffer if an error occurs while reading.

In many cases, this function’s performance will be adequate and the ease of use and type safety tradeoffs will be worth it. However, there are cases where you need more control over performance, and in those cases you should definitely use BufRead::read_line directly.

§Errors

This function forces you to handle errors because the output (the String) is wrapped in a Result. See BufRead::read_line for the errors that can occur. If any error occurs, you will get an Err, so you don’t have to worry about your buffer being empty or partially full.

§Examples

fn main() -> io::Result<()> {
    let stdin = read_line(&mut io::stdin())?;
    println!("Stdin was:");
    println!("{}", stdin);
    Ok(())
}