Sling Academy
Home/Golang/Creating Custom Math Libraries in Go for Reuse

Creating Custom Math Libraries in Go for Reuse

Last updated: November 24, 2024

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.

Next Article: Handling Very Large and Very Small Numbers in Go

Previous Article: Generating and Validating Checksums Using Numbers in Go

Series: Numbers and Math in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant