CLI Calculator - Reading User Input in Rust | Rust by Examples (Lesson 2)
Video: CLI Calculator - Reading User Input in Rust | Rust by Examples (Lesson 2) by Taught by Celeste AI - AI Coding Coach
Watch full page →CLI Calculator - Reading User Input in Rust
In this lesson, you'll build a simple command-line calculator in Rust that reads user input, converts it into numbers, and performs arithmetic operations. The example demonstrates how to use Rust's standard input, string parsing, and match expressions for clean and effective operator handling.
Code
use std::io;
fn main() {
// Create mutable strings to hold user input
let mut input1 = String::new();
let mut input2 = String::new();
let mut operator = String::new();
// Prompt and read the first number
println!("Enter the first number:");
io::stdin()
.read_line(&mut input1)
.expect("Failed to read line");
let num1: i32 = input1.trim().parse().expect("Please enter a valid number");
// Prompt and read the second number
println!("Enter the second number:");
io::stdin()
.read_line(&mut input2)
.expect("Failed to read line");
let num2: i32 = input2.trim().parse().expect("Please enter a valid number");
// Prompt and read the operator
println!("Enter an operator (+, -, *, /):");
io::stdin()
.read_line(&mut operator)
.expect("Failed to read line");
let op = operator.trim();
// Perform calculation based on operator using match expression
let result = match op {
"+" => num1 + num2,
"-" => num1 - num2,
"*" => num1 * num2,
"/" => {
if num2 == 0 {
println!("Error: Division by zero");
return;
} else {
num1 / num2
}
}
_ => {
println!("Invalid operator");
return;
}
};
// Print the result
println!("{} {} {} = {}", num1, op, num2, result);
}
Key Points
- Use
io::stdin().read_line(&mut buffer)to read user input into a mutable string. - Apply
.trim()to remove whitespace and newline characters from input strings. - Convert strings to numbers with
.parse(), specifying the target type likei32. - Use
matchexpressions to handle different operators cleanly and safely. - Check for edge cases like division by zero to avoid runtime errors.