How to Create Your Own Package in Golang?
Last Updated :
15 Sep, 2021
Go language is a high-level programming language developed at Google Inc. A high-level language is in simple words, the programming language category created by humans for human understanding. Before we jump onto high terminologies as packages, modules, functions, etc. let's write the most basic program in Golang. The most basic program in the programming world is the Hello world.
Go
package main
import "fmt"
// Main function
func main() {
fmt.Printf("Hello World!")
}
Since Go lang run is not supported on this IDLE, I've attached a screenshot of the output below.
The first program that prints hello world on the console. The output screen is likely to be as in the image if you use Visual Studio on the Windows platform.
We must have seen this program a million times until now but do we really understand what's in it? Or do we just scan the keywords written in the code and copy-paste it and then implement in further in our programs? We all know the answer! But let's try to understand the code now.
package main
This statement makes the package available as an executable code of the program. A package can simply be explained as a capsule that binds multiple pieces of code together which may contain multiple libraries, multiple functionalities all included in one capsule that can be easily used in any program by the user by just importing or mentioning the package.
import "fmt"
Here fmt is a built-in package provided by Go lang. All basic print operations, scan operations, etc fall under this package.
func main()
It is a simple declaration of the function main that holds the executable driver code.
fmt.Printf("Hello world!")
In this line, it may appear simple but there is a logic behind that simple dot ('.') that lies in between fmt and Printf. The dot is a mediator that performs an important search. The term preceding the dot here is the package name and the name succeeding the dot here is the set of function that belongs to the package mentioned before the dot. Printf is a function that lies under the fmt package and it offers the "Printing input string (in this case) on the console in one line".
As discussed earlier, fmt is a pre-built package, developed by someone else. We find many things in these pre-built codes but why can we not try building our own packages? Well, building our own packages increases the readability, reusability, and efficiency among our work organization as it will be specific about the work we do and not the rest of the world! Let's see a demo of how to build a simple new package.
Well, before you proceed you need to ensure the following steps, these are essential to ensure smooth workflow:
- Check your GOPATH in environment variables and set it to the directory which contains all Go files.
- Create a new folder with the name of the package you wish to create.
- In the folder created in step 2, create your go file that holds the Go package code you wish to create.
- It is recommended that you name your file the same name as your package name, it is not mandatory but just ensures less chaotic imports.
- Watch the detailed demo below to get an idea of how things work! :)
Go
package calculator
// I'm creating a simple calculator that
// performs one calculator operation as per the
// user's choice. For readability of code,
// I named the package as "calculator"
// And remember, the first executable line
// must always be as mentioned above:
// the keyword package followed by a name
// that you wish to give to your package*
//* indicates very very important
import "fmt"
// importing fmt package for basic
// printing & scan operations
func Calc() {
// a simple Calc function that contains
// all code within and has no return
// type mentioned
// Println prints the input string in new line
fmt.Println("Welcome to calculator")
fmt.Println("********************MAIN MENU*************************")
fmt.Println("1. Add")
fmt.Println("2. Subtract")
fmt.Println("3. Multiply")
fmt.Println("4. Divide")
fmt.Println("******************************************************")
var choice int
// choice will store the user's
// input as per the menu shown above
fmt.Scan(&choice)
var a, b int
// After the choice of operation, user
// will be asked to enter 2 int
// values one by one to perform
// the operation on
fmt.Println("Enter value of a: ")
fmt.Scan(&a)
fmt.Println("Enter value of b: ")
fmt.Scan(&b)
if( choice == 1 ){
// choice 1 activates this part --> addition
ans := a + b
fmt.Println("Answer = ", ans)
} else if( choice == 2 ){
// choice 2 activates this part --> subtraction
ans := a - b
fmt.Println("Answer = ", ans)
} else if( choice == 3 ){
// choice 3 activates this part --> multiplication
ans := a * b
fmt.Println("Answer = ", ans)
} else {
// choice 4 activates this part --> division
// remember not to enter second value as 0
// as that would raise a DivideByZero error
// or may display infinity
ans := a / b
fmt.Println("Answer = ", ans)
}
fmt.Println("******************************************************")
fmt.Println("Thank you for using calculator! Have a nice day ahead. ^-^")
fmt.Println("******************************************************")
}
Well, package codes are different from normal file codes. So our process doesn't end here. Writing your code inside the package file is the first step. After writing the code, save your file as the name of the package that you mentioned in your first line of code. For Example, In my case:
calculator.go
After naming your file, you need to perform some important steps. As this is a package that you are creating, you will need the go compiler to build and compile your code. And for that, go to the folder where your package file code is located. Open command prompt in that directory. Run the following command in cmd:
go install
This command will compile your Go package and make it ready for use. Now create the main file to use your first package. Here, we are sharing the code from our main file
Go
package main
import "myprograms/go-packages/calculator"
// this is the local directory
// where my package file is located
func main() {
calculator.Calc()
// name of my package dot name of the
// function I wish to execute in that
// package
}
Save your code and execute the following command on cmd in the directory where the main file is
located -----------> "go build file_name.go"
For example:
go build main.go
And now your main file has compiled successfully. To execute it, enter the following command on your cmd:
"file_name"
For example: main
You will notice that the calc function executes exactly as coded. A demo from my package run is shown below for reference.
This is the calculator package code file and in the terminal section are the commands that need to be executed and the outputs are also shown in the screenshot mentioned above. Also, take note of the directories where I've opened the terminal and what commands have been executed.
This is the main code file where the package is imported and executed. Observe how simple the main file code becomes once you create a package. The package can be reused a million times in any code now. If you make it available on the cloud then anyone on the web can use it. Notice the commands on the terminal and the directory as they're very important.
Similar Reads
How to Create Modules in Golang? Go has included support for versioned modules as proposed here since 1.11 with the initial prototype as vgo. The concept of modules in Go was introduced to handle the problem of dependencies within your Go applications. Several packages are collected and combined to form a module which is stored in
3 min read
How to Take Input from the User in Golang? Scanln function can be used to take the input from the user in the Golang. Below is the example of taking input from the user: C // Golang program to show how // to take input from the user package main import "fmt" // main function func main() { // Println function is used to // display o
2 min read
How to Install "golang-gopkg-mgo.v2-dev" Package on Ubuntu? mgo is a MongoDB driver for the Go language that implements a rich and well-tested selection of features under a very simple API following standard Go idioms. mgo ha0.s long gone unmaintained and does not support new features of new versions of MongoDB. Anyways, let's learn how to install it on Ubun
1 min read
How to Install a package with GO get? In the Go language, we can use the go get command to download and install the packages and dependencies. Various repositories have the support to go get like Azure Repos Git and GitHub Repos. Executable is installed in the directory named by the GOBIN environment variable which defaults to $GOPATH/b
2 min read
fmt Package in GoLang Prerequisite: Packages in GoLang and Import in GoLang Technically defining, a package is essentially a container of source code for some specific purpose. Packages are very essential as in all programs ranging from the most basic programs to high-level complex codes, these are used. A package ensur
13 min read
strconv package in Golang Go language provides a strconv package that implements conversions to and from string representations of basic data types. To access the functions of the strconv package you need to import the strconv package in your program with the help of the import keyword. .strconv-golang-table { border-collaps
5 min read
How to use strconv.Itoa() Function in Golang? Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides an Itoa() function which is equivalent to FormatInt(int64(x), 10). Or in other words, Itoa() function returns the string representation of x
2 min read
How to Create an Empty File in Golang? Like other programming languages, Go language also allows you to create files. For creating a file it provides Create() function, this function is used to create or truncates the given named file. This method will truncate the file, if the given file is already exists. This method will create a file
2 min read
How to use strconv.Quote() Function in Golang? Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides a Quote() function which is used to find a double-quoted Go string literal representing str and the returned string uses Go escape sequences
2 min read
How to Generate Random String/Characters in Golang? We might want to generate random strings or even sets of characters to perform some operations or add certain string-related functionality into an application. We can randomly get a character from a set of characters, randomize the order of characters of a given string or generate a random string. W
6 min read