Reading Input
So far, our programs have only printed things out. But what if we want the user to type something in? That's where input comes in!
In Rust, reading input takes a few steps. Let's learn the pattern!
Reading a Word or Name
Here's how you read a line of text from the user:
Let's break this down:
use std::io;— This brings in Rust's input/output tools.let mut input = String::new();— We create an empty string to store what the user types. We needmutbecauseread_linewill change it.io::stdin().read_line(&mut input).unwrap();— This reads one line of text from the user and puts it intoinput.input.trim()— This removes the extra newline character at the end. When you press Enter, that gets included too!.unwrap()— This tells Rust "I'm sure this will work, just do it!" (We'll learn better error handling later.)
Try it out! Type your name when the program runs:
Reading Numbers
What if you want the user to type a number? You need one extra step — parsing. That means converting the text into a number.
The key new part is .parse().unwrap(). This converts the trimmed text into a number. We also tell Rust what type of number we want with : i32 (a 32-bit integer).
Try typing a number:
Reading Multiple Values
Sometimes you need to read more than one thing. Just repeat the pattern with a new String::new() each time:
Each input needs its own String::new() and its own read_line() call. This is important — you can't reuse the same string variable without clearing it first!
The Input Pattern
Here's a handy summary of the pattern you'll use over and over:
For text:
- Create a mutable string:
let mut input = String::new(); - Read into it:
io::stdin().read_line(&mut input).unwrap(); - Trim the newline:
let text = input.trim();
For numbers:
- Create a mutable string:
let mut input = String::new(); - Read into it:
io::stdin().read_line(&mut input).unwrap(); - Trim and parse:
let num: i32 = input.trim().parse().unwrap();
Now let's practice with some exercises!