Rust Tutorials: std::io (Read, Write)

beginner
23 min

Rust Tutorials: std::io (Read, Write)

Welcome to the fourth lesson of the Rust tutorial series! In this lesson, we'll dive into the std::io module, which allows us to read and write data to various sources like the console, files, and even network streams. Let's get started!

Introduction 🎯

The std::io module is a fundamental part of Rust's standard library. It provides functions for input and output operations, making it possible to interact with various data sources and sinks.

Before we dive into the examples, let's understand some basic types that we'll be using:

  1. std::io::Write: A trait that defines the methods for writing data.
  2. std::io::Read: A trait that defines the methods for reading data.
  3. std::io::BufWriter<W>: A struct that provides buffered writing for W, which can be std::fs::File or other types implementing std::io::Write.
  4. std::io::BufRead<R>: A struct that provides buffered reading for R, which can be std::fs::File or other types implementing std::io::Read.

Reading from the Console 💡

To read input from the console, we can use the std::io::stdin() function, which returns a std::io::Stdin object. Then, we can use the read_line() function from the std::io module to read a line of text.

rust
use std::io; fn main() { let mut input = String::new(); io::stdin() .read_line(&mut input) .expect("Failed to read line"); println!("You entered: {}", input); }

In this example, we create a mutable string variable input to store the entered text. Then, we read a line from the console using io::stdin().read_line(&mut input) and store the result in the input variable. Lastly, we print the entered text.

Quiz

Writing to the Console 📝

Writing to the console is straightforward. We can use the println!() macro, which writes formatted output to the console.

rust
use std::io; fn main() { println!("Hello, World!"); }

In this example, we use the println!() macro to write "Hello, World!" to the console.

Reading and Writing to Files ✅

To read and write files in Rust, we can use the std::fs::File type, which implements both std::io::Read and std::io::Write. Let's create a simple example where we write some text to a file and then read it back.

rust
use std::fs::File; use std::io::{Write, BufWriter, Read, BufRead}; fn main() -> std::io::Result<()> { let mut file = BufWriter::new(File::create("example.txt")?); writeln!(file, "Hello, World!")?; let mut buffer = String::new(); let mut file = File::open("example.txt")?; let reader = BufRead::new(file); for line in reader.lines() { let line = line?; println!("{}", line); } Ok(()) }

In this example, we create a file named example.txt and write the text "Hello, World!" to it using writeln!(file, "Hello, World!"). Then, we open the file and read its content line by line using reader.lines(). For each line, we print it to the console.

That's it for this lesson! In the next lesson, we'll learn about more advanced features of Rust's std::io module, such as error handling and streaming. See you there!