🎓 A1Learner
🔍
0 of 142 lessons completed

Rust User Input

User input is text a person types while a program runs. Rust reads a typed line into an empty String.

Prepare an empty String

The use line brings in the io tools. The String starts empty and mut — read_line will fill it:

use std::io;
let mut line = String::new();

Read one typed line into it

read_line fills the String with what the user types. expect guards the read: if it fails, the program stops with your message:

io::stdin()
    .read_line(&mut line)
    .expect("could not read your answer");

Trim what arrived

The typed line arrives with spaces and the Enter key's newline still on it. trim cuts them from both ends:

let raw = "  Ferris \n";
println!("[{}]", raw.trim());

Turn text into a number

parse reads the text as the type you name. The fresh let shadows the text with the number:

let text = "42";
let age: u32 = text.trim().parse().expect("a number, please");
println!("next year: {}", age + 1);

How much arrived?

Save the Ok value and you can print the count. Type Ferris, press Enter, and 7 bytes arrive: six letters and the newline:

let mut line = String::new();
let bytes = io::stdin().read_line(&mut line).unwrap();
println!("bytes = {}", bytes);

Example

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 your answer");
    let name = name.trim();
    println!("Hello, {name}!");
    println!("Your name has {} letters.", name.chars().count());
}

Key points

  • A small set of tools is always available without any use line — that free set is called the prelude
  • read_line returns a Result: the read might fail.
  • Adding .expect("message") stops the program with your message if it did
  • The keyboard fills the String: typed input is text first, and a value second.

In this example, the output shows one real run, where the user typed Ferris. The program prints its question first. String::new() makes an empty String. read_line fills it with the typed line. The String is lent as &mut name, because the method must change it. expect guards the read: if it had failed, the program would stop with the given message. trim() removes the newline that arrived with the Enter key, and the fresh let shadows the padded original. Finally, {name} inside the text prints the variable by name, and chars().count() counts its 6 letters.

Note

In many languages, input arrives already converted to a number.

In Rust it always arrives as text first.

You choose the conversion.

So a bad answer can be handled instead of crashing mysteriously.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Why must the String you pass to read_line be declared with mut?