- Get link
- X
- Other Apps
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
- Printing a Line:
fn main() {
println!("Hello, world!"); // Prints with a newline
}
- Formatted Output:
fn main() {
let name = "Alice";
let age = 25;
println!("Name: {}, Age: {}", name, age); // String interpolation
}
- 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:
io::stdin()accesses the standard input.read_line(&mut input)reads user input into the mutableinputvariable..expect()handles errors during input operations..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 (i32here).
File I/O in Rust
Rust supports file handling through the std::fs module.
- 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");
}
- 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
| Operation | Function/Method | Example |
|---|---|---|
| Print Output | println!, print! | println!("Hello, {}!", name); |
| Read Input | io::stdin | io::stdin().read_line(&mut input); |
| File Output | File::create, write_all | Write text to a file |
| File Input | fs::read_to_string | Read 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.
- Get link
- X
- Other Apps

Comments
Post a Comment