Rust might be fast and safe, but what good is a program if it can’t talk to the user? In this section, we’ll explore how to get input from users and show output on the screen. Let’s dive in!
1. Printing Output to the Console
Rust provides the println!
and print!
macros to display output.
a) println!
(with a newline)
fn main() {
println!("Hello, Rustaceans!");
}
Automatically adds a newline at the end.
b) print!
(without a newline)
fn main() {
print!("Hello, ");
print!("world!");
}
Does not add a newline, so the output stays on the same line.
2. Formatting Output
Use placeholders to format text dynamically!
fn main() {
let name = "Rust";
let version = 1.73;
println!("Welcome to {} v{}!", name, version);
}
Pro Tip: Use {}
as a placeholder, and Rust will insert variables in order.
3. Taking User Input
Rust uses std::io
to read input.
a) Basic Input with stdin()
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());
}
Why trim()
? read_line()
captures the newline character, so trim()
removes it.
b) Converting Input to a Number
use std::io;
fn main() {
let mut number = String::new();
println!("Enter a number: ");
io::stdin().read_line(&mut number).expect("Failed to read line");
let number: i32 = number.trim().parse().expect("Invalid number!");
println!("You entered: {}", number);
}
Pro Tip: Always convert strings to numbers before doing calculations!
Wrapping Up
Now you can make your Rust programs interactive! You’ve learned: Printing output (println!
, print!
), Formatting text, Taking user input with stdin()
, Converting input into numbers
Go forth and make Rust chatty!
0 Comments