In Rust, input and output operations are primarily handled through the std::io module. Rust provides robust and type-safe mechanisms for interacting with the standard input, output, and error streams.


Output in Rust

Output is generally performed using macros like print! and println!.

Basic Output Examples

  1. Printing a Line:

fn main() { println!("Hello, world!"); // Prints with a newline }
  1. Formatted Output:

fn main() { let name = "Alice"; let age = 25; println!("Name: {}, Age: {}", name, age); // String interpolation }
  1. Printing Without a Newline:

fn main() { print!("This is on the same line."); print!(" Still on the same line."); }

Input in Rust

Reading input is usually done via the std::io module, specifically with std::io::stdin.

Basic Input Example


use std::io; fn main() { let mut input = String::new(); // Create a mutable String to store input println!("Enter your name:"); io::stdin() .read_line(&mut input) // Read a line from standard input .expect("Failed to read line"); // Handle potential errors println!("Hello, {}!", input.trim()); // `trim` removes trailing newline }

Explanation:

  1. io::stdin() accesses the standard input.
  2. read_line(&mut input) reads user input into the mutable input variable.
  3. .expect() handles errors during input operations.
  4. .trim() removes trailing whitespace or newline characters.

Reading Numeric Input

Reading numbers requires parsing the input string, as stdin reads all input as text.


use std::io; fn main() { let mut input = String::new(); println!("Enter a number:"); io::stdin() .read_line(&mut input) .expect("Failed to read line"); let number: i32 = input .trim() .parse() .expect("Please enter a valid number"); // Convert string to integer println!("You entered: {}", number); }

Explanation:

  • input.trim() ensures no trailing whitespace interferes with parsing.
  • parse() attempts to convert the string into the specified type (i32 here).

File I/O in Rust

Rust supports file handling through the std::fs module.

  1. Writing to a File:

use std::fs::File; use std::io::Write; fn main() { let mut file = File::create("example.txt").expect("Failed to create file"); file.write_all(b"Hello, file!").expect("Failed to write to file"); }
  1. Reading from a File:

use std::fs; fn main() { let content = fs::read_to_string("example.txt").expect("Failed to read file"); println!("File content: {}", content); }

Summary

OperationFunction/MethodExample
Print Outputprintln!, print!println!("Hello, {}!", name);
Read Inputio::stdinio::stdin().read_line(&mut input);
File OutputFile::create, write_allWrite text to a file
File Inputfs::read_to_stringRead the entire content of a file into a string

Rust's approach to I/O is type-safe, efficient, and well-integrated into its error-handling mechanisms, ensuring robust and reliable code.

Comments

Popular posts from this blog