In this article, we'll explore how to create custom math libraries in Go, which you can reuse across different projects. We will start with simple utility functions and then move on to more complex structures.
Getting Started with Basic Functions
Let's begin with creating basic math functions like addition and subtraction. First, create a new Go file named math_util.go.
package mathutil
// Add two integers
func Add(x int, y int) int {
return x + y
}
// Subtract two integers
func Subtract(x int, y int) int {
return x - y
}
This simple library provides two basic operations: addition and subtraction. Next, we'll integrate this library into an application.
Intermediate: Adding More Functions
To expand our library, we can add more complex operations such as multiplication, division, and a function to find the factorial of a number. Update your math_util.go to include these:
package mathutil
// Multiply two integers
func Multiply(x int, y int) int {
return x * y
}
// Divide two integers
func Divide(x int, y int) (int, error) {
if y == 0 {
return 0, fmt.Errorf("division by zero")
}
return x / y, nil
}
// Factorial of a non-negative integer
func Factorial(n int) (int, error) {
if n < 0 {
return 0, fmt.Errorf("negative number")
}
result := 1
for i := 2; i <= n; i++ {
result *= i
}
return result, nil
}
Here, we've added multiplication, division with proper error handling for division by zero, and a factorial function.
Advanced: Structs and Methods
For advanced operations, we can create a struct that holds more complex mathematical objects, like vectors or matrices, and operate on them. Let's create a vector struct as an example:
package mathutil
type Vector struct {
X, Y, Z float64
}
// Add two vectors
func (v1 *Vector) Add(v2 Vector) Vector {
return Vector{
X: v1.X + v2.X,
Y: v1.Y + v2.Y,
Z: v1.Z + v2.Z,
}
}
// Calculate the dot product of two vectors
func (v1 *Vector) Dot(v2 Vector) float64 {
return v1.X*v2.X + v1.Y*v2.Y + v1.Z*v2.Z
}
We defined a Vector struct and implemented methods to add two vectors and compute their dot product. This is useful in various scientific and graphics applications.
Testing Your Library
Testing is crucial to ensure the correctness of your library functions. You can test these functions using Go's testing package:
package mathutil
import "testing"
func TestAdd(t *testing.T) {
result := Add(2, 3)
expected := 5
if result != expected {
t.Errorf("Expected %d, got %d", expected, result)
}
}
// Add more test cases for other functions in a similar fashion
To run the tests, use the command:
go test ./...With this setup, you've created a comprehensive math library that you can reuse and extend in different Go projects.