Skip to main content
Rust Programming
CHAPTER 06 Beginner

User Input and Output

Updated: May 18, 2026
5 min read

# CHAPTER 6

User Input and Output

1. Chapter Introduction

A program is much more useful if it can interact with the user. In this chapter, we will build our first interactive CLI (Command Line Interface) application. We will learn how to read text from the keyboard, deal with standard input/output streams, and parse that text into numbers so we can perform math on user input.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Import the standard Input/Output library (std::io).
  • Read a line of text from the user's keyboard.
  • Understand basic error handling with .expect().
  • Parse strings into integers or floats.
  • Trim whitespace from input strings.

3. The std::io Library

To read input, we need to bring the io library from the Standard Library (std) into our program's scope. We do this using the use keyword at the top of our file.
rust
12345
use std::io; // Brings the io module into scope

fn main() {
    println!("Please enter your name:");
}

4. Reading User Input

Let's ask the user for their name and print it back to them.
rust
1234567891011121314151617
use std::io;

fn main() {
    println!("Please enter your name:");

    // 1. Create a MUTABLE, empty String to hold the input
    // String::new() is a function that creates a new, empty string.
    let mut user_name = String::new();

    // 2. Read the line from standard input
    io::stdin()
        .read_line(&mut user_name) // Pass a mutable reference to our string
        .expect("Failed to read line"); // Handle potential errors

    // 3. Print the result
    println!("Hello there, {}", user_name);
}

What is happening here?

  • &mut username: readline needs to modify the string we created. The & indicates a Reference (which we will learn later), and mut means it is allowed to change it.
  • .expect(): If the OS fails to read the input (e.g., the user hits an invalid shortcut key), the program will crash safely and print the custom error message. Rust forces you to handle errors explicitly!

5. Parsing Input into Numbers

When read_line reads input, it *always* reads it as a String. If the user types 25, Rust sees the text "25\n" (with a hidden newline character at the end because the user pressed 'Enter'). To do math, we must parse it into an integer.
rust
123456789101112131415161718
use std::io;

fn main() {
    println!("Enter your age:");

    let mut age_input = String::new();

    io::stdin()
        .read_line(&mut age_input)
        .expect("Failed to read line");

    // 1. Trim removes whitespace and the hidden '\n' newline character
    // 2. Parse converts the string into a number
    // 3. We define the type (u32) so parse() knows what to convert it into
    let age: u32 = age_input.trim().parse().expect("Please type a valid number!");

    println!("Next year you will be {}", age + 1);
}

6. Mini Project: User Profile App

Let's combine reading strings and numbers!
rust
123456789101112131415161718192021
use std::io;

fn main() {
    println!("--- Welcome to the Profile Builder ---");
    
    // Read Name
    println!("Enter your username:");
    let mut name = String::new();
    io::stdin().read_line(&mut name).expect("Failed to read name");

    // Read Weight
    println!("Enter your weight in kg:");
    let mut weight_input = String::new();
    io::stdin().read_line(&mut weight_input).expect("Failed to read weight");
    
    let weight: f64 = weight_input.trim().parse().expect("Invalid weight entered");

    println!("\nProfile Created!");
    println!("Username: {}", name.trim()); // Trim to remove the newline from printing
    println!("Weight: {} kg", weight);
}

7. Common Mistakes

  • Forgetting &mut: If you write readline(username) without the &mut, the compiler will fail. readline requires a mutable reference to the variable so it can inject the data into it.
  • Forgetting .trim() before parsing: If a user types 10 and hits enter, the string is "10\n". If you try to parse "10\n" into an integer, it will crash because \n is not a number. Always use .trim().parse().
  • Forgetting .expect(): readline and parse both return a Result type. If you don't handle the potential failure using .expect(), the code will not compile.

8. Best Practices

  • Handle errors gracefully: While .expect() crashes the program, later in the course we will learn how to use match to loop and ask the user to try again without crashing!

9. Exercises

  1. 1. Write a program that asks the user for the length and width of a rectangle.
  1. 2. Read both inputs as strings, trim them, and parse them into f64.
  1. 3. Calculate the Area and print it to the screen.

10. MCQs with Answers

Question 1

How do you import the standard input/output library in Rust?

Question 2

What type of variable does readline require to store the user's input?

Question 3

How do you create an empty String in Rust?

Question 4

Why must we pass &mut stringname to readline?

Question 5

What is the purpose of .expect("Error") at the end of readline?

Question 6

What format is the data in immediately after readline successfully executes?

Question 7

Which method removes whitespace and hidden newline characters from a string?

Question 8

Which method attempts to convert a string into a number?

Question 9

How does .parse() know whether to convert the string into an integer or a float?

Question 10

What happens if you try to .parse() the string "hello" into an i32?

11. Interview Questions

  • Q: Why does Rust force developers to use .expect() or handle errors when taking user input, unlike languages like Python?
  • Q: Describe the process of converting a user's terminal input into a mathematical integer in Rust.

12. FAQs

  • Can I hide the user's input (like typing a password)? Not with standard std::io. You would need to add a third-party "crate" (package) like rpassword to your Cargo.toml.

13. Summary

Interactive programs require careful data handling. Rust's std::io library makes reading terminal input straightforward, but the compiler forces you to handle potential errors via .expect() and cleanly convert String data via .trim().parse(). This strictness guarantees that invalid data won't silently corrupt your application logic.

14. Next Chapter Recommendation

Now that we can take user input and parse it, we need to make decisions based on that data. In Chapter 7: Conditional Statements, we will learn how to use if, else if, and Rust's incredibly powerful match statement to control the flow of our application.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·