Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Rust Index

📄 std::io — I/O traits — Read, Write, BufRead, stdin, stdout

Core I/O traits and standard streams. BufReader wraps any Read for efficient buffered reading. io::Result<T> is used throughout.

Docs: doc.rust-lang.org

📋 Types, Functions & Methods

NameSignatureDescription
io::stdin()fn stdin() -> StdinReturn handle to stdin
io::stdout()fn stdout() -> StdoutReturn handle to stdout
io::stderr()fn stderr() -> StderrReturn handle to stderr
stdin.read_linefn read_line(&self, buf: &mut String) -> Result<usize>Read one line into String
stdin.lines()fn lines(self) -> Lines<Self>Iterator over lines from stdin
BufReader::newfn new(inner: R) -> BufReader<R>Create buffered reader
BufWriter::newfn new(inner: W) -> BufWriter<W>Create buffered writer
Read::read_to_stringfn read_to_string(&mut self, buf: &mut String) -> Result<usize>Read all bytes as UTF-8
Write::write_allfn write_all(&mut self, buf: &[u8]) -> Result<()>Write all bytes
Write::flushfn flush(&mut self) -> Result<()>Flush write buffer
BufRead::linesfn lines(self) -> Lines<Self>Iterator over lines
BufRead::read_linefn read_line(&mut self, buf: &mut String) -> Result<usize>Read line into buf
io::Errorstruct ErrorI/O error type
io::Result<T>type Result<T> = Result<T, io::Error>Alias for Result with io::Error
io::copyfn copy(reader: &mut R, writer: &mut W) -> Result<u64>Copy all bytes
io::Cursorstruct Cursor<T>In-memory Read/Write/Seek over slice/Vec
io::empty()fn empty() -> EmptyReader that always returns EOF
io::sink()fn sink() -> SinkWriter that discards all data
writeln!macro writeln!(writer, fmt, ...)Write formatted line to writer
eprintln!macro eprintln!(fmt, ...)Print formatted line to stderr

💡 Example

Save as main.rs in a Cargo project and run with cargo run.

use std::io::{self, BufRead, Write};

fn main() -> io::Result<()> {
    let stdin  = io::stdin();
    let stdout = io::stdout();
    let mut out = io::BufWriter::new(stdout.lock());

    writeln!(out, "=== Line Echo (Ctrl-D to stop) ===")?;

    for (i, line) in stdin.lock().lines().enumerate() {
        let line = line?;
        writeln!(out, "{:3}: {}", i + 1, line.to_uppercase())?;
    }

    // In-memory I/O with Cursor
    use std::io::{Cursor, Read};
    let data = b"Hello, Rust I/O!";
    let mut cursor = Cursor::new(data);
    let mut buf    = String::new();
    cursor.read_to_string(&mut buf)?;
    writeln!(out, "Cursor: {}", buf)?;

    out.flush()?;
    Ok(())
}
// cargo run

🏠 Index  |  std::fs →