Open In App

How to Create Your Own Package in Golang?

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Golang - Hello World

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:

  1. Check your GOPATH in environment variables and set it to the directory which contains all Go files.
  2. Create a new folder with the name of the package you wish to create.
  3. In the folder created in step 2, create your go file that holds the Go package code you wish to create.
  4. 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.
  5. 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.



Last Updated : 15 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads