Rust User Input
Programs become interactive when they accept information from a person. Rust reads keyboard text through the standard library. Everything arrives as text first, so numbers need a conversion step. Reading input resembles taking an order at a counter: you ask, you listen, you check the answer, and you act on it.
Reading One Line
The stdin().read_line() method waits for the user to type a line and press Enter. It stores the text inside a mutable String.
use std::io;
fn main() {
let mut name = String::new();
println!("What is your name?");
io::stdin()
.read_line(&mut name)
.expect("Could not read the line");
println!("Hello, {}", name.trim());
}Why the String Must Be Mutable
The method writes text into the variable you pass in. The keyword mut grants that permission, and &mut lends the variable to the method.
The Hidden New Line
The Enter key adds a new-line character to the stored text. The trim() method removes it along with extra spaces. Skip trimming and your output breaks into two lines.
Typed: Ravi [Enter] Stored: "Ravi\n" trim(): "Ravi"
Understanding the Result
The read_line method returns a Result value, which signals success or failure. Calling expect stops the program with your message if reading fails. Keyboard reading rarely fails, so expect works well for small programs.
Reading a Number
Typed digits arrive as text. The parse method converts text to a number type. Tell Rust the target type with a type annotation or a turbofish.
use std::io;
fn main() {
let mut text = String::new();
println!("Enter your age:");
io::stdin().read_line(&mut text).expect("Read failed");
let age: u32 = text.trim().parse().expect("Please type a number");
println!("Next year you will be {}", age + 1);
}Handling Wrong Input
People mistype. The expect call crashes the program on bad input, which frustrates users. A match expression handles the problem politely.
match text.trim().parse::<u32>() {
Ok(age) => println!("Age saved: {age}"),
Err(_) => println!("That was not a valid number"),
}Asking Until the Answer Is Valid
A loop repeats the question until the user provides a usable value. The program below keeps asking for a positive number.
use std::io;
fn main() {
let number = loop {
let mut text = String::new();
println!("Type a number from 1 to 10:");
io::stdin().read_line(&mut text).expect("Read failed");
match text.trim().parse::<u32>() {
Ok(n) if n >= 1 && n <= 10 => break n,
_ => println!("Try again."),
}
};
println!("You chose {number}");
}
Ask --> Read --> Trim --> Parse --+--> valid? --yes--> Use value ^ | +---------------no----------------+
Showing the Prompt on the Same Line
The print! macro does not flush its text immediately. Call flush to display the prompt before the program waits.
use std::io::{self, Write};
fn main() {
print!("Enter a city: ");
io::stdout().flush().unwrap();
let mut city = String::new();
io::stdin().read_line(&mut city).unwrap();
println!("City: {}", city.trim());
}Reading Several Values from One Line
The split_whitespace method splits a line into words. Convert each word as needed.
let line = "12 30";
let parts: Vec<i32> = line
.split_whitespace()
.map(|p| p.parse().unwrap())
.collect();
println!("Sum: {}", parts[0] + parts[1]);Common Mistakes
Skipping trim() tops the list. The stored text still carries the new-line character, so a parse call fails with an invalid digit error even though the user typed a valid number.
Reusing one String inside a loop without clearing it creates another trap. The read_line method appends to existing text instead of replacing it. Call clear() before each read, or declare a new string inside the loop.
Choosing the wrong number type causes failures too. Parsing a negative value into a u32 returns an error, because unsigned types reject minus signs.
Practice Ideas
- Build a program that asks for two numbers and prints their sum, difference, and product.
- Create a guessing game that keeps asking until the player finds a hidden number.
- Read a full sentence and print how many words it holds.
Input Safety Tips
Treat every typed value as untrusted. Check the range of numbers, limit the length of text, and reject empty answers. A program that validates input once at the entry point avoids many bugs deeper in the code. Clear prompts also help users type the right thing the first time.
Key Points
- Use
io::stdin().read_line(&mut text)to read a line. - Call
trim()to remove the new-line character. - Convert text to numbers with
parse. - Prefer
matchoverexpectwhen users may type wrong values. - Flush output when a prompt uses
print!.
