
Getting Started with Rust: Building a Simple Command-Line Calculator
Prerequisites
Before we start, make sure you have the following installed:
- Rust (You can install it from rustup.rs)
- A text editor or IDE (like Visual Studio Code, IntelliJ Rust, etc.)
Creating a New Rust Project
First, let’s create a new Rust project. Open your terminal and run:
cargo new calculator
cd calculatorThis command creates a new directory named calculator with the necessary files for a Rust project.
Writing the Calculator Code
Open the src/main.rs file in your text editor. We will write our calculator logic here. Below is the complete code for a simple command-line calculator:
use std::io;
fn main() {
loop {
println!("Enter the first number:");
let mut first_input = String::new();
io::stdin().read_line(&mut first_input).expect("Failed to read line");
let first_number: f64 = match first_input.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Please enter a valid number");
continue;
}
};
println!("Enter an operator (+, -, *, /):");
let mut operator_input = String::new();
io::stdin().read_line(&mut operator_input).expect("Failed to read line");
let operator = operator_input.trim();
println!("Enter the second number:");
let mut second_input = String::new();
io::stdin().read_line(&mut second_input).expect("Failed to read line");
let second_number: f64 = match second_input.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Please enter a valid number");
continue;
}
};
let result = match operator {
"+" => first_number + second_number,
"-" => first_number - second_number,
"*" => first_number * second_number,
"/" => {
if second_number == 0.0 {
println!("Cannot divide by zero");
continue;
}
first_number / second_number
},
_ => {
println!("Invalid operator");
continue;
}
};
println!("The result is: {}", result);
}
}Code Explanation
- Imports: We import the
std::iomodule to handle user input.
- Main Loop: The program runs in an infinite loop, allowing the user to perform multiple calculations until they terminate the program.
- User Input:
- The program prompts the user to enter the first number, operator, and second number.
- It utilizes
io::stdin().read_line()to read user input andtrim().parse()to convert the input string into af64number.
- Error Handling:
- If the user inputs a non-numeric value, the program informs them and continues to the next iteration.
- It checks for division by zero and handles invalid operators.
- Calculating the Result: Based on the operator, the program performs the corresponding arithmetic operation.
Running the Calculator
To run your calculator, execute the following command in your terminal:
cargo runYou should see output prompting you to enter numbers and an operator. For example:
Enter the first number:
5
Enter an operator (+, -, *, /):
*
Enter the second number:
4
The result is: 20Best Practices
- Input Validation: Always validate user input to prevent runtime errors.
- Error Handling: Use
matchorif letto handle potential errors gracefully. - Code Structure: Keep your code modular. For larger projects, consider separating logic into functions or modules.
- Documentation: Comment your code to explain complex logic and maintain readability.
Conclusion
In this tutorial, we created a simple command-line calculator in Rust. We covered user input handling, basic arithmetic operations, and error management. This project serves as a foundation for understanding Rust's syntax and its capabilities for building command-line applications.
