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.
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());
}| Step | Action | Input/Value | Variable State | Output |
|---|---|---|---|---|
| 1 | Initialize mutable String variable 'input' | N/A | input = "" | |
| 2 | Prompt user to type input | User sees prompt (implicit) | input = "" | |
| 3 | Read line from stdin into 'input' | User types: Hello Rust! | input = "Hello Rust!\n" | |
| 4 | Trim newline from 'input' | N/A | input = "Hello Rust!\n" | |
| 5 | Print trimmed input | N/A | input = "Hello Rust!\n" | You typed: Hello Rust! |
| 6 | Program ends | N/A | input = "Hello Rust!\n" |
| Variable | Start | After Step 3 | After Step 5 | Final |
|---|---|---|---|---|
| input | "" | "Hello Rust!\n" | "Hello Rust!\n" | "Hello Rust!\n" |
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