![]() |
VOOZH | about |
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.
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 calculatorThis will be project structure and you have to organize your files in this format.
Each of these files (add.go, subtract.go, etc.) will contain specific 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
}
main.goIn main.go file you have to import necessary packages and handle CLI arguments:
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 5Output: