0
0
Rustprogramming~5 mins

Reading input basics in Rust

Choose your learning style9 modes available
Introduction

Reading input lets your program get information from the user while it runs. This makes your program interactive and useful.

When you want to ask the user for their name and greet them.
When you need to get numbers from the user to do calculations.
When you want to let the user choose options in a menu.
When you want to read commands typed by the user in a console app.
Syntax
Rust
use std::io;

let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");

You need to create a mutable String variable to store the input.

read_line reads the input and adds it to the String variable.

Examples
This reads a line from the user and prints it back.
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);
}
This example removes extra spaces and newlines from the input before printing.
Rust
use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed to read line");
    let trimmed = input.trim();
    println!("Trimmed input: {}", trimmed);
}
Sample Program

This program asks the user for their name, reads it, removes extra spaces, and then greets them.

Rust
use std::io;

fn main() {
    println!("Please enter your name:");
    let mut name = String::new();
    io::stdin().read_line(&mut name).expect("Failed to read line");
    let name = name.trim();
    println!("Hello, {}!", name);
}
OutputSuccess
Important Notes

Always make the String variable mutable with mut to store input.

Use trim() to remove newline characters from the input.

Handle errors with expect or match to avoid crashes.

Summary

Reading input lets your program talk to the user.

Use a mutable String and io::stdin().read_line() to get input.

Trim the input to clean it before using.