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
4. Reading User Input
Let's ask the user for their name and print it back to them.
rust
What is happening here?
-
&mut username:readlineneeds to modify the string we created. The&indicates a Reference (which we will learn later), andmutmeans 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
Whenread_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
6. Mini Project: User Profile App
Let's combine reading strings and numbers!
rust
7. Common Mistakes
-
Forgetting
&mut: If you writereadline(username)without the&mut, the compiler will fail.readlinerequires a mutable reference to the variable so it can inject the data into it.
-
Forgetting
.trim()before parsing: If a user types10and hits enter, the string is"10\n". If you try to parse"10\n"into an integer, it will crash because\nis not a number. Always use.trim().parse().
-
Forgetting
.expect():readlineandparseboth return aResulttype. 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 usematchto loop and ask the user to try again without crashing!
9. Exercises
-
1.
Write a program that asks the user for the
lengthandwidthof a rectangle.
-
2.
Read both inputs as strings, trim them, and parse them into
f64.
- 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) likerpasswordto yourCargo.toml.
13. Summary
Interactive programs require careful data handling. Rust'sstd::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 useif, else if, and Rust's incredibly powerful match statement to control the flow of our application.