Open In App

Creating a Command Line calculator in Golang - Step by Step tutorial

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this tutorial we are going to create a basic command line application in Golang, we will highlight some core principles including Go Modules, Go Packages, Go Functions, the fmt package, and work with command line parameters.

Step 1) Initialize Go Module

Now we have to create a Go module and for this navigate to your project directory and run following command, this command will initializes Go module and creates go.mod file which shall be used to resolve dependencies for the project.

go mod init calculator

Step 2) Go Package Structure

This will be project structure and you have to organize your files in this format.

1

Each of these files (add.go, subtract.go, etc.) will contain specific functions.

Step 3: Writing Calculator Functions

add.go

package operations

// Add function returns the sum of two numbers
func Add(a, b float64) float64 {
return a + b
}

subtract.go

package operations

// Subtract function returns the difference between two numbers
func Subtract(a, b float64) float64 {
return a - b
}

multiply.go

package operations

// Multiply function returns the product of two numbers
func Multiply(a, b float64) float64 {
return a * b
}

divide.go

package operations

import "errors"

// Divide function returns the quotient of two numbers
func Divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero is not allowed")
}
return a / b, nil
}

Step 4: Building the CLI in main.go

In main.go file you have to import necessary packages and handle CLI arguments:

Go
package main

import (
    "calculator/operations"
    "fmt"
    "os"
    "strconv"
)

func main() {
    if len(os.Args) < 4 {
        fmt.Println("Usage: go run main.go [add|subtract|multiply|divide] num1 num2")
        return
    }

    operation := os.Args[1]
    num1, _ := strconv.ParseFloat(os.Args[2], 64)
    num2, _ := strconv.ParseFloat(os.Args[3], 64)

    switch operation {
    case "add":
        fmt.Printf("Result: %f\n", operations.Add(num1, num2))
    case "subtract":
        fmt.Printf("Result: %f\n", operations.Subtract(num1, num2))
    case "multiply":
        fmt.Printf("Result: %f\n", operations.Multiply(num1, num2))
    case "divide":
        result, err := operations.Divide(num1, num2)
        if err != nil {
            fmt.Println(err)
        } else {
            fmt.Printf("Result: %f\n", result)
        }
    default:
        fmt.Println("Invalid operation. Use [add|subtract|multiply|divide].")
    }
}

Step 5: Rebuild and Run the Code

After making such changes, it is expected that, the folder structure is modified in a way which does not lead to circular imports being resolved by Golang, to run your program, go to the terminal and change into your project directory then type the following:

go run main.go add 10 5

Output:

1




Next Article
Article Tags :

Similar Reads