Sub topic 1
Getting a Handle to Standard Input
Prerequisites
This chapter assumes basic Rust syntax, ownership of String, mutable references, match, and Result. You should also know how to run a program with cargo run.
Getting a Handle to Standard Input
Standard input, or stdin, is the stream from which a program receives input. In a terminal, stdin usually comes from the keyboard. It can also come from a file or another program through a pipe.
Rust provides stdin through std::io::stdin(). This function returns a Stdin handle. You pass a mutable reference to a String when reading a line.
Reading One Line with `read_line`
read_line appends the next line to the provided String. The line normally includes its ending newline. The method returns a Result<usize>, where the successful value is the number of bytes read.
use std::io;
fn main() {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("could not read input");
println!("Received: {input:?}");
}The &mut input argument gives read_line permission to change the string. The string must be mutable because the method stores the input in it.
Handling the `Result`: `expect` and the `?` Operator
Input can fail because of an operating-system error. Rust represents this possibility with io::Result. The expect method extracts the successful value. If an error occurs, it stops the program and prints the supplied message.
Use expect when an input failure is unrecoverable in a small program.
For reusable or production code, return the error to the caller with ?:
use std::io;
fn main() -> io::Result<()> {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
println!("Received: {input:?}");
Ok(())
}The ? operator returns early when the operation fails. Therefore, main must return a compatible Result type. On success, the program continues after the expression.
Exercise
Which return type lets main use ? with read_line?
Show answer
A compatible result type, such as io::Result<()>.