0
0
Rustprogramming~5 mins

Handling input values in Rust

Choose your learning style9 modes available
Introduction

We use input handling to get information from the user while the program is running. This lets the program react to what the user types.

When you want to ask the user for their name.
When you need to get a number from the user to do math.
When you want the user to choose an option from a menu.
When you want to read a line of text from the user.
When you want to pause the program until the user presses Enter.
Syntax
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());
}

We create a mutable String to store what the user types.

read_line reads the input and adds it to the String.

Examples
This example asks for the user's name and greets them.
Rust
use std::io;

fn main() {
    let mut name = String::new();
    println!("Enter your name:");
    io::stdin().read_line(&mut name).expect("Failed to read line");
    println!("Hello, {}!", name.trim());
}
This example reads a number as text, then converts it to an integer.
Rust
use std::io;

fn main() {
    let mut number = String::new();
    println!("Enter a number:");
    io::stdin().read_line(&mut number).expect("Failed to read line");
    let number: i32 = number.trim().parse().expect("Please type a number!");
    println!("You typed the number: {}", number);
}
Sample Program

This program waits for the user to type something and then shows it back.

Rust
use std::io;

fn main() {
    let mut input = String::new();
    println!("Please type something and press Enter:");
    io::stdin().read_line(&mut input).expect("Failed to read line");
    println!("You typed: {}", input.trim());
}
OutputSuccess
Important Notes

Always use trim() to remove the newline character from the input.

Use expect() to handle errors simply during input reading.

To convert input to numbers, use parse() and handle possible errors.

Summary

Input handling lets your program talk with the user.

Use io::stdin().read_line() to get user input as text.

Remember to trim and convert input when needed.