Sub topic 1
Getting a handle to standard input
Every Rust program that reads from the keyboard, a pipe, or a redirected file starts the same way. It asks the standard library for a handle to standard input. This chapter explains what that handle is, what it shares with other handles, and how to use it safely. The later chapters build on it to read and parse text.
Prerequisites
This chapter assumes you can do the following:
- Write and run a small Rust program with
cargo run. - Read basic Rust syntax:
let,mut, functions,match. - Tell
Stringfrom&strand pass a&mut Stringto a function. - Understand
Resultand the?operator at a basic level.
You do not need to know traits in depth. The chapter introduces the two traits that matter here, Read and BufRead, and says when to import them.
What standard input is
Standard input, or stdin, is a byte stream that the operating system gives every process when it starts. On Unix-like systems it is file descriptor 0. On Windows it is the console input handle. The program does not choose where the bytes come from. The shell that launches it decides:
- With no redirection, the bytes come from the terminal. You type, and the terminal sends a line to the program when you press Enter.
- With
<, as incargo run < data.txt, the bytes come from a file. - With a pipe, as in
printf '3\n4\n' | cargo run, the bytes come from another program.
Your code looks the same in all three cases. This is why input code written against stdin works equally well for interactive use and for scripts.
Calling `std::io::stdin()`
The function std::io::stdin() returns a value of type Stdin. This value is a handle: it does not own the stream and cannot create one. It is a reference to a single buffer that the standard library keeps for the whole process.
use std::io;
fn main() {
let stdin = io::stdin();
println!("got a handle: {:?}", stdin);
}The usual style is use std::io; followed by io::stdin(). It makes clear that stdin belongs to the I/O module. It also leaves room for other items from std::io, such as io::Result, io::Write, and io::stdout.
Some points to know about the handle:
- You never open or close it. Dropping a
Stdindoes not close file descriptor 0. - Calling
stdin()is cheap. It does not read anything and does not wait. Nothing blocks until you ask for data. - It is not tied to a particular function. You can call
io::stdin()again wherever you need it, or pass the handle around.
One shared buffer behind every handle
The standard library reads stdin in chunks and keeps the unread bytes in a buffer. That buffer is global to the process, and every Stdin handle points at it. Two handles do not each get their own copy of the input. They read from the same position in the same stream.
use std::io;
fn main() -> io::Result<()> {
let first = io::stdin();
let second = io::stdin();
let mut a = String::new();
let mut b = String::new();
first.read_line(&mut a)?;
second.read_line(&mut b)?;
println!("first handle read: {:?}", a.trim_end());
println!("second handle read: {:?}", b.trim_end());
Ok(())
}Run it with piped input:
printf 'one\ntwo\n' | cargo runThe output is:
first handle read: "one"
second handle read: "two"The second handle picks up where the first stopped. No data is lost or read twice. The next chapter covers read_line in detail. Here it only shows that the handles share state.
The buffer is protected by a mutex, so Stdin can be used from several threads. Each call to a method such as read_line takes the mutex for the duration of the call and releases it afterwards.
Locking the handle
A Stdin method takes the mutex on every call. If you read thousands of lines, that is thousands of lock and unlock operations. You can take the lock once instead:
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let stdin = io::stdin();
let mut handle = stdin.lock();
let mut line = String::new();
let bytes = handle.read_line(&mut line)?;
println!("read {bytes} bytes: {:?}", line.trim_end());
Ok(())
}stdin.lock() returns a StdinLock. While you hold it, no other handle can read, and StdinLock implements BufRead. That trait gives you read_line, lines, and other buffered methods. Because read_line here comes from a trait, you must write use std::io::BufRead;. Without the import, the compiler reports that no method named read_line exists on StdinLock, even though the method is there.
Since Rust 1.61, lock() returns a StdinLock<'static>, so it does not borrow from the handle it was called on. This means io::stdin().lock() works as one expression, even though the temporary Stdin is dropped at the end of the statement. Older compilers required you to bind the handle to a variable first. The chapter on locked iteration uses this form with lines().
The lock is not reentrant
The mutex is not reentrant. If a thread holds a StdinLock and then calls a method on a Stdin handle, the second call waits for a lock that its own thread already holds. The program can then hang forever.
Which methods you get, and which traits to import
Stdin and StdinLock expose different sets of methods, and some come only from traits.
| Type | Method | Where it comes from | Import needed |
|---|---|---|---|
| `Stdin` | `read_line` | Inherent method | None |
| `Stdin` | `lines` | Inherent method (Rust 1.62 and later) | None |
| `Stdin` | `lock` | Inherent method | None |
| `Stdin` | `read_to_string` | `Read` trait | `use std::io::Read;` |
| `StdinLock` | `read_line` | `BufRead` trait | `use std::io::BufRead;` |
| `StdinLock` | `lines` | `BufRead` trait | `use std::io::BufRead;` |
| `StdinLock` | `read_to_string` | `Read` trait | `use std::io::Read;` |
If a method seems to be missing, the cause is almost always a missing trait import. The compiler usually names the trait in its error message.
When you call a Read method on a handle you stored in a variable, that variable must be declared mut, because Read::read_to_string takes &mut self:
use std::io::{self, Read};
fn main() -> io::Result<()> {
let mut stdin = io::stdin();
let mut text = String::new();
stdin.read_to_string(&mut text)?;
println!("{} bytes", text.len());
Ok(())
}Reading everything at once has its own chapter. This example only shows the mut and the import.
Checking whether stdin is a terminal
Sometimes a program should behave differently when a person is typing than when data is piped in. For example, it might skip prompts for piped input. Since Rust 1.70 the IsTerminal trait answers this question:
use std::io::{self, IsTerminal};
fn main() {
if io::stdin().is_terminal() {
println!("stdin is a terminal: a person may be typing");
} else {
println!("stdin is redirected: a file or pipe supplies the data");
}
}Compare cargo run with echo hi | cargo run. The first prints the terminal message and the second prints the redirected one.
Common mistakes
- Wrapping stdin in your own
BufReader.Stdinis already buffered.BufReader::new(io::stdin())adds a second buffer on top of it. The outer reader may pull in more bytes than you consume. Another handle created later then misses those bytes, because they sit in your reader. Usestdin.lock()for aBufRead, orio::stdin().lines(). - Expecting a read when you create the handle.
io::stdin()does no I/O. A program that seems to hang is waiting inside a read call, not insidestdin(). - Holding a lock too long. A
StdinLockkept alive across a long computation blocks every other thread that wants to read. Drop it, or end its scope, when you are done. - Forgetting that the stream is consumed. Bytes you have read are gone. There is no rewinding stdin. If you need the data twice, store it in a
StringorVec.
Summary of the model
io::stdin() gives you a cheap, copy-free handle to one process-wide buffer. Any number of handles read the same stream in order. lock() trades per-call locking for a single lock held across many reads, and it unlocks the BufRead methods. With this model in place, the next chapter turns to reading one line into a String.
Exercise
A program creates let a = io::stdin(); and let b = io::stdin();. Input is x\ny\n. It calls a.read_line(&mut s1) and then b.read_line(&mut s2). What do s1 and s2 contain, and why?
Show answer
s1 is "x\n" and s2 is "y\n". Both handles refer to the same process-wide buffer, so the second read continues from where the first one ended. It does not start again from the beginning of the input.
Exercise
This code fails to compile with "no method named lines found for struct StdinLock". What is missing, and what is a one-line fix?
let stdin = io::stdin();
for line in stdin.lock().lines() { / ... / }
Show answer
The BufRead trait is not in scope. lines on a StdinLock is a BufRead method. Adding use std::io::BufRead; fixes the error.
Exercise
Why can calling io::stdin().read_line(&mut s) while the same thread holds a StdinLock hang the program?
Show answer
Every Stdin method takes the same mutex that StdinLock already holds, and that mutex is not reentrant. The thread waits for a lock it owns itself, so it never proceeds. The fix is to read through the StdinLock for the whole scope.