Input lets a program get information from the user or other sources. Output shows results or messages back to the user. Without input and output, a program cannot interact with people or other programs.
0
0
Why input and output are required in Rust
Introduction
When you want to ask the user for their name and greet them.
When you need to read numbers from a file and show the total.
When a program must display error messages or results on the screen.
When you want to get commands from the user and respond accordingly.
Syntax
Rust
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
println!("You typed: {}", input.trim());
}Input: Use io::stdin().read_line(&mut variable) to get user input as text.
Output: Use println! macro to show messages or results on the screen.
Examples
This example asks for a name and then greets the user.
Rust
use std::io;
fn main() {
let mut name = String::new();
io::stdin().read_line(&mut name).expect("Failed to read line");
println!("Hello, {}!", name.trim());
}This example only shows output without input.
Rust
fn main() {
println!("Welcome to the program!");
}This example reads a number from the user, converts it to an integer, and prints it.
Rust
use std::io;
fn main() {
let mut number = String::new();
io::stdin().read_line(&mut number).expect("Failed to read line");
let number: i32 = number.trim().parse().expect("Please type a number!");
println!("You entered number: {}", number);
}Sample Program
This program asks the user to enter their favorite color and then repeats it back.
Rust
use std::io;
fn main() {
println!("Enter your favorite color:");
let mut color = String::new();
io::stdin().read_line(&mut color).expect("Failed to read line");
println!("Your favorite color is {}!", color.trim());
}OutputSuccess
Important Notes
Always trim input to remove extra spaces or newlines.
Input is usually read as text; convert it if you need numbers.
Output helps users understand what the program is doing.
Summary
Input lets programs get information from users or files.
Output shows results or messages to users.
Together, input and output make programs interactive and useful.