-
Book Overview & Buying
-
Table Of Contents
The Rust Programming Handbook
By :
While a "Hello, World!" program is an excellent first step, it only touches the surface of what Rust is capable of. Let’s take it a step further by building a simple command-line calculator that can perform basic arithmetic operations based on user input.
This small project will introduce you to key concepts in Rust, including the following:
std::ioparse() methodFirst, create a new Rust project using Cargo:
cargo new cli_calculator
cd cli_calculator
Open src/main.rs in your favorite IDE and let’s start coding!
We will build a simple calculator that does the following:
+, -, *, or /)Here’s the complete code, followed by a deeper explanation (Don’t worry if you don’t fully understand the code below. This is just to get used to the Rust code. We will get into all the concepts and constructs used in the example below in the upcoming chapters. Take this as a trailer!):
// Import the standard input/output library to handle user input
use std::io;
fn main() {
// Display a welcome message to introduce the program
println!("Welcome to the Rust CLI Calculator!");
// Prompt the user to enter the first number
// We use a helper function `get_number` to handle input validation
let num1 = get_number("Enter the first number: ");
// Prompt the user to enter the second number
let num2 = get_number("Enter the second number: ");
// Prompt the user to enter an operation
println!("Enter an operation (+, -, *, /):");
// Create a mutable string to store the user's input
let mut operation = String::new();
// Read the user's input and store it in `operation`
io::stdin().read_line(&mut operation).expect("Failed to read input");
// Trim any whitespace (e.g., newline) from the input
let operation = operation.trim();
// Perform the calculation based on the chosen operation
let result = match operation {
"+" => Some(num1 + num2), // Addition
"-" => Some(num1 - num2), // Subtraction
"*" => Some(num1 * num2), // Multiplication
"/" => {
// Before dividing, check that the second number is not zero
if num2 != 0.0 {
Some(num1 / num2) // Division
} else {
println!("Error: Division by zero is not allowed.");
None // Return None if division by zero is attempted
}
}
_ => {
// If the user enters an invalid operation, print an error message
println!("Invalid operation. Please enter +, -, *, or /.");
None // Return None to indicate an invalid operation
}
};
// If the result is valid (not None), print the result
if let Some(res) = result {
println!("Result: {}", res);
}
}
// This function prompts the user to enter a number and ensures valid input
fn get_number(prompt: &str) -> f64 {
loop { // Infinite loop until valid input is provided
println!("{}", prompt); // Display the prompt message
let mut input = String::new(); // Create a new mutable string for user input
io::stdin().read_line(&mut input).expect("Failed to read input"); // Read input
// Try to convert the input string into a floating-point number (f64)
match input.trim().parse::<f64>() {
Ok(num) => return num, // If parsing succeeds, return the number
Err(_) => println!("Invalid number. Please enter a valid numeric value."), // If parsing fails, prompt again
}
}
}
Let’s look at a detailed explanation:
io::stdin().read_line()):get_number() function):parse::<f64>() converts the input string into a floating-point numbermatch for decision-making:None for invalid operations, preventing incorrect calculationsif let Some(res) = result):Some(value)), it prints itNow, compile and run your calculator:
cargo run
Try entering different numbers and operations. If you enter invalid input, the program will prompt you until a valid number is provided.
This simple CLI calculator introduced several fundamental Rust concepts:
std::io::stdin()match expressions and loops for input validation.trim() and .parse()This is just the beginning! Don’t worry if you don’t understand everything now; this was meant to give you an idea of what Rust code looks like and to help you become familiar with the Rust syntax!