Building a Small Calculator in Rust!

Building a Small Calculator in Rust!

ยท

2 min read

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.

Step 1: Setting up the Project

  1. Create a New Rust Project: Open your terminal and execute the following command to create a new Rust project named calculator:

     cargo new calculator
    
  2. Navigate to the Project Directory: Enter the project directory using:

     cd calculator
    

Step 2: Writing the Calculator Logic

  1. 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)
     }
    

Step 3: Running the Calculator

  1. Run the Calculator: Execute the following command in your terminal from the project directory:

     cargo run
    
  2. 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.

  3. Exit the Calculator: Type quit to exit the calculator loop.

Conclusion

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://medium.com/techwasti

https://www.youtube.com/@maheshwarligade

https://techwasti.com/series/spring-boot-tutorials

https://techwasti.com/series/go-language

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

ย