Go – Custom Package

By | 25/10/2019

A package is nothing but a directory containing one or more Go source files.
We can define two types of packages: executable package and utility package.
An executable package is the main application that we will be running.
A utility package is not self-executable, instead, it enhances the functionality of an executable package by providing utility functions and other important assets.

In this post, we will see how to create a custom package and how to use it in a main application.
We open Visual Studio Code and in the folder src we create two folders, called utility and applicationOne
The first will contain our Custom Package, called operation.go, instead the second one will contain our executable package, called main.go:

[OPERATION.GO]

package utility

// Add function is a public function
func Add(val1 int, val2 int) int {
	return val1 + val2
}



[MAIN.GO]

package main

// we import the package fmt and our custom package
import (
	"fmt"
	"utility"
)

func main() {
	fmt.Printf("The sum of 5 with 34 is: %d \n", utility.Add(5, 34))
}



Now, in order to verify that everything works fine, we open a terminal and we run the commands:
go build
./applicationOne



Category: Go Tags:

Leave a Reply

Your email address will not be published.