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:
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 mainimport "fmt"func main() {fmt.Println("Hello World")}
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.
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.
This tutorial aims at creating a Go package that helps developers easily implement the stack and queue methods in their projects.
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
A file ending with the .go
extension will be created using the touch
command.
touch stacky.go
In the .go
file created, all the structs needed to successfully implement the methods of stacks and queues were added.
//name of packagepackage stacky// Stack struct with a field of a slice of itemstype Stack struct {items []int}// Queue struct with a field of a slice of itemstype Queue struct {items []int}//Push method adds to the top of the stackfunc (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 itemfunc (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 isfunc (s *Stack) Peek() int {removable:=s.items[len(s.items)-1]return removable}//IsEmpty method queries whether the stack is currently emptyfunc (s *Stack) IsEmpty() bool {if len(s.items)==0 {return true}return false}//Enqueue method adds an item to the queuefunc (q *Queue) Enqueue(i int) {q.items=append(q.items, i)}//Dequeue method removes an item from the queuefunc (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.
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 mainimport ("fmt"stacks "github.com/yemmyharry/stacky")func main() {//myStack is a variable of an empty stackmyStack := stacks.Stack{}//the push method adds to the empty stackmyStack.Push(10)myStack.Push(20)myStack.Push(30)//prints out the current state of myStackfmt.Println(myStack)//views the top of the stackfmt.Println(myStack.Peek())// removes an item from the stackfmt.Println(myStack.Pop())//views the new top of the stackfmt.Println(myStack.Peek())//prints out the current state of myStackfmt.Println(myStack)//checks if the stack is emptyfmt.Println(myStack.IsEmpty())//myQueue is a variable of an empty queuemyQueue := stacks.Queue{}//enqueue method adds to the queuemyQueue.Enqueue(12)myQueue.Enqueue(20)myQueue.Enqueue(50)//prints out the current state of myQueuefmt.Println(myQueue)// removes an item from the queuemyQueue.Dequeue()//prints out the new state of myStackfmt.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.