Fuad Olatunji

Fuad Olatunji

How to create a package in golang.

How to create a package in golang.

Create your own custom go packages for re-usability.

In golang we use a package using the import keyword.

For a single package:

import "fmt"

For multiple packages, we use the multi line syntax:

import (
    "fmt"
    "math"
    "log"
)

Similar to initializing multiple variables:

var (
    a int
    b int
    c int
)

Ever wondered what the package main at the top of every go file means?

It's a package declaration, all go files must belong to a package.

The go run command can only execute go files in the main package.

Now that we know about packages lets move to creating our own package, we would be creating a furthermaths package.

Don't worry your furthermaths package would be easier than regular mathematics 🙂.

Step 1: Create a project directory

e.g

mkdir $GOPATH/src/github.com/fuadop/furthermaths

cd $GOPATH/src/github.com/fuadop/furthermaths

go mod init

Step 2: Create a go file

You can name it whatever you wish. I would go with math.go.

touch math.go

Step 3: Declare the package

Instead of adding package main to the top of the file, we would be adding our package name. i.e

package furthermaths

We would be defining only one function in our package, which is the Add function.

Before we continue, there is something you must know when defining functions in a custom package.

  1. To make your function accessible outside the package, the function name must begin with an uppercase letter. The same is applicable to variables.

This is similar to private and public members of a class in OOP (Object Oriented Programming).

Now that you know that, let us go on with defining our Add function.

package furthermaths

// Adds multiple amount of numbers
func Add(nums ...int) int {
    var result int
    for _, num := range nums {
        result += num
    }
    return result
}

We have finally created a furthermaths package with an Add function.

To use this function in another project, you need to install the package using the go get command.

go get github.com/fuadop/furthermaths

The function can be used like so:

package main

import (
    "fmt"

    "github.com/fuadop/furthermaths"
)

func main() {
    fmt.Println(furthermaths.Add(1, 2, 3, 4))
}

Running the above command would print 10 to the console.

10

To get the package source code, click here.

 
Share this