Mastering Go Packages: Building a Reusable Calculator Library
This challenge will guide you through the process of creating your own reusable package in Go. You'll build a simple calculator library that can perform basic arithmetic operations. Understanding packages is fundamental to organizing larger Go projects and sharing functionality efficiently.
Problem Description
Your task is to create a Go package named calculator that exposes functions for performing addition, subtraction, multiplication, and division. This package should be importable by other Go programs, allowing them to leverage your calculator functionality without needing to reimplement it.
Key Requirements:
- Create a new Go module.
- Define a package named
calculator. - Implement four exported functions within the
calculatorpackage:Add(a, b int) int: Returns the sum ofaandb.Subtract(a, b int) int: Returns the difference ofaandb.Multiply(a, b int) int: Returns the product ofaandb.Divide(a, b int) (int, error): Returns the quotient ofaandb. This function should return anerrorif division by zero is attempted.
- Ensure all functions intended for external use are exported (start with an uppercase letter).
- Write a separate
mainpackage that imports and uses yourcalculatorpackage to demonstrate its functionality.
Expected Behavior:
The calculator package should correctly perform arithmetic operations. The Divide function must handle division by zero gracefully by returning a descriptive error. The main package should successfully import and call the functions from your calculator package.
Edge Cases to Consider:
- Division by zero.
- Large integer values (within Go's
intlimits).
Examples
Example 1:
Input (to calculator package functions):
// In main.go
package main
import (
"fmt"
"your_module_path/calculator" // Replace with your actual module path
)
func main() {
sum := calculator.Add(10, 5)
difference := calculator.Subtract(10, 5)
product := calculator.Multiply(10, 5)
quotient, err := calculator.Divide(10, 5)
fmt.Printf("Sum: %d\n", sum)
fmt.Printf("Difference: %d\n", difference)
fmt.Printf("Product: %d\n", product)
if err == nil {
fmt.Printf("Quotient: %d\n", quotient)
}
}
Output:
Sum: 15
Difference: 5
Product: 50
Quotient: 2
Explanation:
The main function calls each of the exported calculator functions with sample inputs and prints their results. The division operation is successful as the divisor is not zero.
Example 2:
Input (to calculator package functions):
// In main.go
package main
import (
"fmt"
"your_module_path/calculator" // Replace with your actual module path
)
func main() {
_, err := calculator.Divide(10, 0) // Attempting division by zero
if err != nil {
fmt.Printf("Error: %s\n", err)
}
}
Output:
Error: division by zero
Explanation:
The Divide function is called with a divisor of zero. It detects this invalid operation and returns a non-nil error object, which the main function then prints.
Constraints
- The
calculatorpackage must be a distinct directory within your Go module. - All functions in the
calculatorpackage that are intended to be used externally must be exported (start with an uppercase letter). - The
Dividefunction must return anerrorof typeerrorwhen division by zero occurs. - Input integers for
Add,Subtract, andMultiplywill be within the standard Gointrange. - The division operation should result in integer division (truncating any remainder).
Notes
- To initialize a Go module, navigate to your project directory in the terminal and run
go mod init your_module_path(replaceyour_module_pathwith a unique identifier for your module, e.g.,github.com/yourusername/calculator). - The
calculatorpackage should reside in a subdirectory namedcalculatorwithin your module. - You will need to create a
mainpackage in a separate directory (e.g.,cmd/mainormain) to test yourcalculatorpackage. - Remember to use the
errorinterface for error handling in Go. Theerrorspackage can be helpful for creating simple error messages. - Think about how you will structure your project directory. A common approach is to have a
calculatordirectory for the package and a separate directory for the main application that uses it.