Reading standard input in Rust
A filter reads lines from stdin, so it composes with every other tool.
use std::io::{self, BufRead, Write};
fn main() -> io::Result<()> {
let stdin = io::stdin();
let stdout = io::stdout();
let mut out = stdout.lock();
let mut total = 0usize;
for line in stdin.lock().lines() {
let line = line?;
if line.trim().is_empty() {
continue;
}
total += line.split_whitespace().count();
writeln!(out, "{:>4} | {}", line.len(), line)?;
}
writeln!(out, "{total} words")?;
Ok(())
}
How it works
stdin().lock().lines()iterates without reallocating.- Each line arrives as a
Result, since IO can fail. - Writing to stdout through a lock avoids flushing per line.
Keywords and builtins used here
OkResultcontinuefnforifinioletmainmutselfuseusize
The run, in numbers
- Lines
- 20
- Characters to type
- 401
- Tokens
- 143
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 82 seconds.
Step 1 of 1 in Input & output, step 6 of 12 in CLI tools & HTTP clients.