Sub topic 1
Getting a handle to standard input
Prerequisites
This chapter assumes you know the following:
- Basic Rust syntax: variables, functions, and
match. Stringversus&str, and what&mutmeans.Resultat a basic level.- How to run a program with
cargo run.
What standard input is
Standard input (stdin) is the stream of bytes a process receives from outside. When you run a program in a terminal, stdin is usually the keyboard. When you pipe data in (cat data.txt | ./app) or redirect a file (./app < data.txt), stdin is that data instead. Your program doesn't need to know which one it is.
Rust does not let you read from stdin through a global function. You first ask the standard library for a handle, which is a value you call reading methods on.
Getting the handle
The function std::io::stdin() returns a value of type Stdin. It takes no arguments and cannot fail.
use std::io;
fn main() {
let stdin = io::stdin();
let mut input = String::new();
stdin
.read_line(&mut input)
.expect("failed to read line");
println!("Read {} bytes", input.len());
}Three things in this program matter for this chapter:
use std::io;brings the moduleiointo scope. You then writeio::stdin(), which makes it clear where the function comes from.Stdin::read_linetakes&self, so thestdinbinding does not need to bemut. TheStringdoes need to bemut, because the method appends to it.- Reading is a separate step. Getting the handle does not read or wait for anything. The program only blocks when you call a reading method such as
read_line.
The next chapter covers read_line itself. For now, treat it as "read one line into this string".
A shared buffer behind every handle
Stdin is not a private connection. It is a handle to one process-wide buffer that all Stdin values share. Because of this, these two forms behave the same:
use std::io;
fn main() {
let mut first = String::new();
let mut second = String::new();
io::stdin().read_line(&mut first).expect("read failed");
io::stdin().read_line(&mut second).expect("read failed");
println!("first: {:?}", first.trim());
println!("second: {:?}", second.trim());
}Each call to io::stdin() returns a handle to the same buffer. The second call continues where the first stopped, and no input is lost or read twice. You can call io::stdin() wherever you need it, or store it once in a variable.
Locking the handle
The shared buffer sits behind a mutex, which is a lock that lets only one thread use the buffer at a time. Each call such as read_line on a Stdin locks and unlocks that mutex. This is correct and convenient for a few reads.
You can also lock once and hold the lock. stdin.lock() returns a StdinLock, which implements the BufRead trait. That trait gives you extra methods such as lines(), which later chapters use.
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
let mut handle = stdin.lock();
let mut input = String::new();
handle
.read_line(&mut input)
.expect("failed to read line");
println!("You typed: {}", input.trim());
}Here use std::io::{self, BufRead}; imports the io module and the BufRead trait. The trait must be in scope for its methods to be callable on handle.
Common mistakes
- Writing
io::stdinwithout parentheses. That names the function and doesn't call it, and the compiler reports a type mismatch or a missing method. - Forgetting
muton theString.read_lineneeds&mut String, so the compiler rejects an immutable binding. - Using a
StdinLockwithout importingBufRead. Methods such aslines()are not found until the trait is imported. - Holding a lock while calling
io::stdin()again on the same thread. Locking twice at once can deadlock, which means the program waits forever. Use the lock you already hold.
Exercise
A program calls io::stdin().read_line(&mut a) and then, on the next line, io::stdin().read_line(&mut b). Does the second call start reading from the beginning of the input again? Why or why not?
Show answer
No. Every call to io::stdin() returns a handle to the same process-wide buffer, so the second call continues from where the first one stopped. The second line of input goes into b.