Trusted answers to developer questions

How to create and utilize packages in Go

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

A package in Go is composed of a series of Go files present in the same directory that allows the inherent code to be reusable in other parts of a Go program.

Go packages can either be:

  1. Built-in
  2. Third-party
  3. Custom-built

1. Built-in packages

The Go Standard Library provides over a hundred core packages available for developers to use and easily manage their programs. Packages provided by the Go Standard Library can be implemented by using a simple import statement.

import "name of package"

For instance, the fmt package is used to format data either to an input or output. The word fmt is actually a shorthand for format.

import "fmt"

An example of this package in action is highlighted below:

package main
import "fmt"
func main() {
fmt.Println("Hello World")
}

2. Third-party packages

Third-party packages are packages that are not originally designed by the creators of the Go programming language. These packages extend some functionality beneficial to developers. They are made by developers for developers.

Third-party packages must be installed before being imported for use. It is usually installed using the keyword below:

go get <link_of_package> 

The keyword go get is used to install binary tools and then create a dependency in the project which can be tracked via the go.sum file. Recent changes were made in Go version 1.16. One of such changes includes installing binary tools via the go get command which is deprecated. The go install command is the recommended method. More information can be found here.

3. Custom-built packages

A custom-built Go package is a package tailored to provide a specific solution and in accordance with the developer’s long-term goals. The utilization of a custom-built package can be done with the import statement.

import "insert_path_of_package_here" 

The path of the package can only be used when the custom package is already available as a directory within the current project. Otherwise, an installation has to be done before it can be imported for use.

Creating Our Package

This tutorial aims at creating a Go package that helps developers easily implement the stack and queue methods in their projects.

Steps

Create and initialize a directory

The first step involves creating a new directory named stacky. In your terminal, type cd into this directory and enable the use of Go modules by using the command:

go mod init <name of package>

It is common practice to prepend your directory name with a link to your GitHub. Therefore, we’ll initialize go mod in the following manner:

go mod init github.com/yemmyharry/stacky

Create a Go file

A file ending with the .go extension will be created using the touch command.

touch stacky.go

Add Codebase

In the .go file created, all the structs needed to successfully implement the methods of stacks and queues were added.

//name of package
package stacky
// Stack struct with a field of a slice of items
type Stack struct {
items []int
}
// Queue struct with a field of a slice of items
type Queue struct {
items []int
}
//Push method adds to the top of the stack
func (s *Stack) Push(i int) {
s.items=append(s.items,i)
}
// Pop method removes from the top element in the stack and returns the removed item
func (s *Stack) Pop() int {
removable:=s.items[len(s.items)-1]
s.items=s.items[:len(s.items)-1]
return removable
}
// Peek method queries what the top element of the stack is
func (s *Stack) Peek() int {
removable:=s.items[len(s.items)-1]
return removable
}
//IsEmpty method queries whether the stack is currently empty
func (s *Stack) IsEmpty() bool {
if len(s.items)==0 {
return true
}
return false
}
//Enqueue method adds an item to the queue
func (q *Queue) Enqueue(i int) {
q.items=append(q.items, i)
}
//Dequeue method removes an item from the queue
func (q *Queue) Dequeue() {
q.items= q.items[1:]
}
  • In Line 2 of the code snippet above the package is named stacky because it is conventional to name a package after it’s directory name.

  • Lines 5 and 9 are structs of the stack and queue respectively.

  • The remaining lines of code are methods of the stack and queue.

Utilise your package

Congratulations, you successfully created a Go package. You can use your Go package locally by simply calling it in another .go file or in another Go package.

To make it public and available for developers, you need to create a git repository and push the code to it. Anyone interested in using the package can simply copy the url and then install it as a dependency in their program by using:

go get github.com/yemmyharry/stacky

Then importing into the desired Go file :

import (
"github.com/yemmyharry/stacky"
)

To demonstrate this, let’s create a directory named “example”. Then initialize it to get our go.mod file before installing the stacky package using the go get command defined above.

package main
import (
"fmt"
stacks "github.com/yemmyharry/stacky"
)
func main() {
//myStack is a variable of an empty stack
myStack := stacks.Stack{}
//the push method adds to the empty stack
myStack.Push(10)
myStack.Push(20)
myStack.Push(30)
//prints out the current state of myStack
fmt.Println(myStack)
//views the top of the stack
fmt.Println(myStack.Peek())
// removes an item from the stack
fmt.Println(myStack.Pop())
//views the new top of the stack
fmt.Println(myStack.Peek())
//prints out the current state of myStack
fmt.Println(myStack)
//checks if the stack is empty
fmt.Println(myStack.IsEmpty())
//myQueue is a variable of an empty queue
myQueue := stacks.Queue{}
//enqueue method adds to the queue
myQueue.Enqueue(12)
myQueue.Enqueue(20)
myQueue.Enqueue(50)
//prints out the current state of myQueue
fmt.Println(myQueue)
// removes an item from the queue
myQueue.Dequeue()
//prints out the new state of myStack
fmt.Println(myQueue)
}

On line 4, we imported the installed package and gave it an alias of stacks which was used in the program. Since this is an executable program, it can be executed using the following command:

go run main.go

The codebase for this tutorial can be found here.

RELATED TAGS

golang
go
go package
edpressocompetition

CONTRIBUTOR

Omoyemi John Arigbanla
Did you find this helpful?