Rust User Input
Programs get much more fun when they can talk with the person using them. In Rust you read a line from the keyboard with std::io::stdin().read_line. It takes a few more words than in some languages, so let us go through it slowly, one piece at a time.
use std::io;
fn main() {
println!("What is your name?");
let mut name = String::new();
io::stdin().read_line(&mut name).expect("could not read a line");
println!("Nice to meet you, {}!", name.trim());
}Priya
What is your name? Nice to meet you, Priya!
When you run this in the editor, the program prints the question and waits. Type a name in the terminal and press Enter.
What each piece does
use std::io;brings Rust's input and output tools into the program, so we can writeio::stdin()instead of the longstd::io::stdin().let mut name = String::new();makes an empty, growable piece of text to store the answer in. It must bemut, because reading will change it.io::stdin()is the keyboard..read_line(&mut name)reads one line and adds it toname. The&mutletsread_linechange our variable; we will understand that fully on the borrowing page..expect("...")says what to do if reading fails: stop the program with that message. Reading from the keyboard almost never fails, but Rust likes you to say what should happen if it does.
Why trim?
When you press Enter, the Enter key itself becomes part of the line, as an invisible newline character at the end. .trim() removes spaces and newlines from both ends. Forget it, and the exclamation mark ends up on the next line.
Reading numbers
read_line always gives you text. To use it as a number, you parse it. Write the type you want on the new variable, and Rust knows what to turn the text into:
use std::io;
fn main() {
println!("How old are you?");
let mut line = String::new();
io::stdin().read_line(&mut line).expect("could not read a line");
let age: u32 = line.trim().parse().expect("please type a whole number");
println!("In ten years you will be {}.", age + 10);
}13
How old are you? In ten years you will be 23.
If the user types something that is not a number, such as "thirteen", parse fails and expect stops the program with your message. On the Result page you will learn how to handle that more gently, and ask again instead.
A little helper function
Because reading a number takes a few lines, people often wrap it in a function and reuse it:
use std::io;
fn read_number() -> i64 {
let mut line = String::new();
io::stdin().read_line(&mut line).expect("could not read a line");
line.trim().parse().expect("please type a whole number")
}
fn main() {
println!("First number:");
let a = read_number();
println!("Second number:");
let b = read_number();
println!("{} x {} = {}", a, b, a * b);
}6 7
First number: Second number: 6 x 7 = 42
Practice exercises
- Ask for the user's favourite colour and print a sentence that uses it.
- Ask for the length and width of a rectangle and print its area.
- Type a word instead of a number in the age program and read the message you get.