Building a Small Calculator in Rust!

Learner, Love to make things simple, Full Stack Developer, StackOverflower, Passionate about using machine learning, deep learning and AI
Search for a command to run...

Learner, Love to make things simple, Full Stack Developer, StackOverflower, Passionate about using machine learning, deep learning and AI
Move beyond traditional RESTful thinking. Learn how to design APIs specifically for MCP (Model Context Protocol) servers. This guide covers the shift in mindset, a practical OpenAPI 3.1 example, and a Spring Boot implementation to make your services ...

Extending Kestra to Every Corner of Your Data Stack. Introduction: The Power of Plugins Imagine you're a master chef. You don't just have one knife - you have specialized tools for every task: a paring knife for delicate work, a chef's knife for chop...
Mastering Complex Orchestration Scenarios. Introduction: The Orchestrator's Toolkit Imagine you're conducting a symphony. You don't just wave your baton - you cue sections, adjust tempo, handle surprises, and ensure harmony. That's what advanced work...
From Data Extraction to Loading - A Practical Guide Introduction: Why ETL Still Matters in the Modern Data Stack Remember when data engineering was "extract, transform, load"? Some say ETL is dead, replaced by ELT, reverse ETL, and data mesh. But her...
Building Blocks of Declarative Orchestration. Introduction: The Power of Simplicity Imagine trying to build a house without understanding bricks, beams, and blueprints. That's what using an orchestration tool without understanding its core concepts f...
In this guide, we'll create a basic command-line calculator application using Rust. The calculator will perform basic arithmetic operations such as addition, subtraction, multiplication, and division.
Create a New Rust Project: Open your terminal and execute the following command to create a new Rust project named calculator:
cargo new calculator
Navigate to the Project Directory: Enter the project directory using:
cd calculator
Open src/main.rs: Replace the existing content with the following code:
use std::io::{self, Write};
fn main() {
loop {
println!("Enter an expression or 'quit' to exit:");
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
let trimmed = input.trim();
if trimmed == "quit" {
println!("Calculator exited.");
break;
}
let result = evaluate_expression(trimmed);
match result {
Ok(value) => println!("Result: {}", value),
Err(err) => println!("Error: {}", err),
}
}
}
fn evaluate_expression(expression: &str) -> Result<f64, &'static str> {
let parts: Vec<&str> = expression.split_whitespace().collect();
if parts.len() != 3 {
return Err("Invalid expression. Please enter in the format: [number] [operator] [number]");
}
let num1: f64 = match parts[0].parse() {
Ok(num) => num,
Err(_) => return Err("Invalid first number"),
};
let operator = parts[1];
let num2: f64 = match parts[2].parse() {
Ok(num) => num,
Err(_) => return Err("Invalid second number"),
};
let result = match operator {
"+" => num1 + num2,
"-" => num1 - num2,
"*" => num1 * num2,
"/" => {
if num2 == 0.0 {
return Err("Division by zero");
}
num1 / num2
}
_ => return Err("Invalid operator"),
};
Ok(result)
}
Run the Calculator: Execute the following command in your terminal from the project directory:
cargo run
Use the Calculator: Enter expressions in the format number operator number, e.g., 5 + 3, 10 * 2, etc. The calculator will provide the result or display an error message if the expression is invalid.
Exit the Calculator: Type quit to exit the calculator loop.
Congratulations! You've built a simple command-line calculator in Rust that performs basic arithmetic operations. This project demonstrates basic input parsing, error handling, and mathematical operations.
Feel free to enhance this calculator by adding more functionality, error checking, or user interface improvements based on your learning goals.
Continue exploring Rust's features and libraries to expand the capabilities of this calculator or embark on new projects. Happy coding!
More such articles:
https://www.youtube.com/@maheshwarligade