Creating a Go Command-Line Calculator

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating the Calculator
  5. Testing and Debugging
  6. Conclusion


Introduction

In this tutorial, we will learn how to create a command-line calculator using the Go programming language. By the end of this tutorial, you will be able to build a calculator that can perform basic mathematical operations.

Prerequisites

Before starting this tutorial, you should have the following prerequisites:

  • Basic knowledge of Go programming language syntax
  • Go installed on your machine

Setup

To set up your environment for developing the calculator, follow these steps:

  1. Install Go on your machine by downloading the appropriate installer from the official Go website (https://golang.org/dl/) and following the installation instructions.

  2. Verify the installation by opening a terminal and running the following command:

    ```
    go version
    ```
    
    You should see the installed Go version.
    
  3. Create a new directory for your project and navigate to it in the terminal:

    ```
    mkdir calculator
    cd calculator
    ```
    
  4. Initialize a new Go module within the project directory:

    ```
    go mod init github.com/your-username/calculator
    ```
    
    This will create a new `go.mod` file that manages the project's dependencies.
    

Creating the Calculator

Now that we have our environment set up, let’s start building our calculator.

First, create a new file called calculator.go in your project directory. This file will contain the main logic for our calculator.

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	fmt.Print("Enter an expression: ")
	expression, _ := reader.ReadString('\n')

	result := calculate(expression)
	fmt.Printf("Result: %f\n", result)
}

func calculate(expression string) float64 {
	// Remove trailing newline character
	expression = strings.TrimSuffix(expression, "\n")

	tokens := strings.Split(expression, " ")
	if len(tokens) != 3 {
		fmt.Println("Invalid expression")
		os.Exit(1)
	}

	operand1, err := strconv.ParseFloat(tokens[0], 64)
	if err != nil {
		fmt.Println("Invalid operand 1:", err)
		os.Exit(1)
	}

	operator := tokens[1]

	operand2, err := strconv.ParseFloat(tokens[2], 64)
	if err != nil {
		fmt.Println("Invalid operand 2:", err)
		os.Exit(1)
	}

	var result float64
	switch operator {
	case "+":
		result = operand1 + operand2
	case "-":
		result = operand1 - operand2
	case "*":
		result = operand1 * operand2
	case "/":
		if operand2 == 0 {
			fmt.Println("Division by zero")
			os.Exit(1)
		}
		result = operand1 / operand2
	default:
		fmt.Println("Invalid operator:", operator)
		os.Exit(1)
	}

	return result
}

This code sets up a basic command-line interface for the calculator. It reads an expression from the user, passes it to the calculate function, performs the necessary operations, and returns the result.

To try out the calculator, run the following command in the terminal:

go run calculator.go

You will be prompted to enter an expression. For example, you can enter 2 + 3 and press Enter. The calculator will evaluate the expression and print the result.

Testing and Debugging

To ensure that our calculator works correctly, let’s add some tests. Create a new file called calculator_test.go in the same directory as calculator.go.

package main

import "testing"

func TestCalculate(t *testing.T) {
	testCases := []struct {
		expression string
		expected   float64
	}{
		{"2 + 3", 5},
		{"4 - 2", 2},
		{"2 * 5", 10},
		{"6 / 3", 2},
		{"10 / 0", 0},
	}

	for _, testCase := range testCases {
		result := calculate(testCase.expression)
		if result != testCase.expected {
			t.Errorf("Expression '%s' returned incorrect result: expected %f, got %f", testCase.expression, testCase.expected, result)
		}
	}
}

In this test code, we define a series of test cases with different expressions and their expected results. The calculate function is called with each expression, and the result is compared with the expected value. If there is a mismatch, an error message is logged.

To run the tests, execute the following command:

go test

If the tests pass, it means our calculator implementation is correct. Otherwise, the failed test case will be displayed with an error message.

Conclusion

Congratulations! You have successfully built a command-line calculator in Go. In this tutorial, you learned how to set up your environment, create the calculator logic, and test it using test cases. By expanding on this foundation, you can enhance the calculator with more advanced features and functionalities.

Remember to explore Go’s standard library and other third-party packages to extend the capabilities of your calculator. Keep practicing and experimenting with Go to become a proficient Go developer.

Happy coding!