Bird
Raised Fist0
Rustprogramming~10 mins

Reading input basics in Rust - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Reading input basics
Start Program
↓
Prompt User
↓
Read Input Line
↓
Store Input in Variable
↓
Use Input
↓
End Program
The program starts, asks the user for input, reads a line from the keyboard, stores it, then uses it before ending.
Execution Sample
Rust
use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed to read line");
    println!("You typed: {}", input.trim());
}
This Rust program reads a line of text from the user and prints it back.
Execution Table
StepActionInput/ValueVariable StateOutput
1Initialize mutable String variable 'input'N/Ainput = ""
2Prompt user to type inputUser sees prompt (implicit)input = ""
3Read line from stdin into 'input'User types: Hello Rust!input = "Hello Rust!\n"
4Trim newline from 'input'N/Ainput = "Hello Rust!\n"
5Print trimmed inputN/Ainput = "Hello Rust!\n"You typed: Hello Rust!
6Program endsN/Ainput = "Hello Rust!\n"
💡 Program ends after printing the user's input.
Variable Tracker
VariableStartAfter Step 3After Step 5Final
input"""Hello Rust!\n""Hello Rust!\n""Hello Rust!\n"
Key Moments - 3 Insights
Why do we need to make 'input' mutable with 'mut'?
Because read_line changes the content of 'input', it must be mutable. See step 1 and 3 in execution_table where 'input' starts empty and then stores user input.
Why does the printed output not show a new line after the input?
The input includes a newline character '\n' from pressing Enter. We use 'trim()' in step 5 to remove it before printing.
What happens if reading input fails?
The program calls 'expect' which will stop the program and show the error message 'Failed to read line'. This is not shown in the table because input succeeded.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the value of 'input' after reading?
A""
B"Hello Rust!"
C"Hello Rust!\n"
DAn error message
💡 Hint
Check the 'Variable State' column at step 3 in execution_table.
At which step does the program print the user's input?
AStep 4
BStep 5
CStep 2
DStep 6
💡 Hint
Look at the 'Output' column in execution_table to find when output occurs.
If we remove 'mut' from 'input', what will happen when running the program?
ACompilation error because 'input' is not mutable
BProgram will run normally
CRuntime error when reading input
DInput will be empty
💡 Hint
Refer to key_moments about why 'input' must be mutable.
Concept Snapshot
Reading input in Rust:
- Create a mutable String: let mut input = String::new();
- Read line: io::stdin().read_line(&mut input).expect("error");
- Input includes newline, use input.trim() to clean
- Use input as needed
- Program ends after processing input
Full Transcript
This Rust program starts by creating a mutable empty string variable called 'input'. It then waits for the user to type something and press Enter. The typed line, including the newline character, is stored in 'input'. The program trims the newline before printing the message 'You typed: ' followed by the user's input. Finally, the program ends. If reading input fails, the program stops with an error message. The key points are that the input variable must be mutable because it changes, and the newline character from pressing Enter is included in the input and usually trimmed before use.

Practice

(1/5)
1. What is the main purpose of using io::stdin().read_line(&mut input) in Rust?
easy
A. To read a line of text input from the user
B. To print text to the console
C. To declare a new variable
D. To create a new thread

Solution

  1. Step 1: Understand the function of read_line

    This function reads a line of input from the user and stores it in a mutable string.
  2. Step 2: Identify the purpose of io::stdin()

    io::stdin() accesses the standard input stream, allowing the program to receive user input.
  3. Final Answer:

    To read a line of text input from the user -> Option A
  4. Quick Check:

    Reading input = B [OK]
Hint: Remember: read_line reads user input into a string [OK]
Common Mistakes:
  • Confusing input reading with printing output
  • Forgetting to make the string mutable
  • Using read_line without a mutable reference
2. Which of the following is the correct way to declare a mutable string variable to store user input in Rust?
easy
A. let input: &str = String::new();
B. let input = String::new();
C. let mut input = String::new();
D. let mut input: &str = String::new();

Solution

  1. Step 1: Identify the need for mutability

    To store user input, the string must be mutable because read_line modifies it.
  2. Step 2: Check the correct syntax for mutable String

    let mut input = String::new(); correctly declares a mutable String variable.
  3. Final Answer:

    let mut input = String::new(); -> Option C
  4. Quick Check:

    Mutable String declaration = A [OK]
Hint: Use 'mut' to allow input string to change [OK]
Common Mistakes:
  • Omitting 'mut' keyword for the input string
  • Using &str instead of String for input storage
  • Declaring input as immutable
3. What will be the output of this Rust code if the user types "hello" and presses Enter?
use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed to read line");
    println!("You typed: {}", input.trim());
}
medium
A. Compilation error
B. You typed: hello
C. You typed:
D. You typed: hello\n

Solution

  1. Step 1: Understand input reading and trimming

    The program reads the input including the newline, but trim() removes whitespace like newlines.
  2. Step 2: Analyze the output statement

    The trimmed input "hello" is printed after "You typed: ".
  3. Final Answer:

    You typed: hello -> Option B
  4. Quick Check:

    Trim removes newline, output = D [OK]
Hint: Remember to trim input to remove newline before printing [OK]
Common Mistakes:
  • Not trimming input, so newline appears in output
  • Expecting raw input without newline removal
  • Confusing compile errors with runtime behavior
4. Identify the error in this Rust code snippet that tries to read user input:
use std::io;

fn main() {
    let input = String::new();
    io::stdin().read_line(&mut input).expect("Failed to read line");
    println!("Input: {}", input);
}
medium
A. The variable 'input' should be mutable
B. Missing 'use std::io::Write;' import
C. read_line should not use '&mut' reference
D. println! macro syntax is incorrect

Solution

  1. Step 1: Check variable mutability

    read_line requires a mutable reference to modify the string, but input is not mutable.
  2. Step 2: Confirm other parts are correct

    Imports and println! syntax are correct; only mutability is missing.
  3. Final Answer:

    The variable 'input' should be mutable -> Option A
  4. Quick Check:

    Mutable variable needed for read_line = C [OK]
Hint: Make input mutable to allow read_line to change it [OK]
Common Mistakes:
  • Forgetting 'mut' keyword for input variable
  • Thinking &mut is not needed for read_line
  • Assuming println! syntax is wrong
5. You want to read a user's age as an integer from input. Which code snippet correctly reads the input, trims it, and converts it to an i32 in Rust?
hard
A. let age = String::new(); io::stdin().read_line(&age).expect("Failed"); let age: i32 = age.trim().parse().unwrap();
B. let age: i32 = io::stdin().read_line().trim().parse().expect("Invalid number");
C. let mut age = String::new(); io::stdin().read_line(age).expect("Failed"); let age: i32 = age.parse().unwrap();
D. let mut age = String::new(); io::stdin().read_line(&mut age).expect("Failed"); let age: i32 = age.trim().parse().expect("Invalid number");

Solution

  1. Step 1: Read input into a mutable String

    Input must be stored in a mutable String variable passed as a mutable reference to read_line.
  2. Step 2: Trim and parse input to i32

    Use trim() to remove whitespace, then parse() to convert to integer, handling errors with expect().
  3. Final Answer:

    let mut age = String::new(); io::stdin().read_line(&mut age).expect("Failed"); let age: i32 = age.trim().parse().expect("Invalid number"); -> Option D
  4. Quick Check:

    Mutable input + trim + parse = A [OK]
Hint: Always trim input before parsing to number [OK]
Common Mistakes:
  • Not making input string mutable
  • Forgetting to trim before parsing
  • Passing input without &mut to read_line
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard