Input/Output (I/O) in Rust

Rust provides a powerful and flexible I/O system in its standard library, allowing you to read from and write to various sources, including the console, files, and network sockets.

Reading from Standard Input

The std::io module provides functions and types to handle input and output in Rust. For reading user input, you can use the read_line function:

use std::io;

fn main() {
 let mut input = String::new();

 println!("Enter your name:");
 io::stdin()
     .read_line(&mut input)
     .expect("Failed to read line");

 println!("Hello, {}!", input.trim());
}
Hello, John Doe!

Writing to Standard Output

To write to the console, you can use the print! and println! macros, or std::io::Write for more control:

use std::io::Write;

fn main() {
 let name = "Alice";
 println!("Hello, {}!", name);

 let message = "Welcome to Rust!";
 io::stdout()
     .write_all(message.as_bytes())
     .expect("Failed to write output");
}

Working with Files

Rust allows you to read from and write to files using std::fs and std::io::BufReader for buffered reading:

use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
 let file = File::open("example.txt").expect("Failed to open file");
 let reader = BufReader::new(file);

 for (index, line_result) in reader.lines().enumerate() {
 let line = line_result.expect("Failed to read line");
 println!("Line {}: {}", index + 1, line);
 }
}

Error Handling in I/O

Rust encourages safe error handling. The expect method is used to panic with a custom message upon failure, but in production code, you should return Result or use match to handle errors gracefully:

fn read_file_contents(filename: &str) -> std::io::Result {
 let mut file = File::open(filename)?;
 let mut contents = String::new();
 file.read_to_string(&mut contents)?;
 Ok(contents)
}

fn main() {
 match read_file_contents("data.txt") {
 Ok(contents) => println!("{}", contents),
 Err(e) => println!("Something went wrong: {}", e),
 }
}

Advanced Concepts

Rust's I/O system supports asynchronous operations, working with byte streams, and more. Check out the following topics for advanced usage: