Creating and Reusing Packages

Creating and Reusing Packages

In this tutorial, we are going to discuss on creating and reusing packages in Go language.

Creating and Reusing Packages

Let’s create a sample program for demonstrating a package. Create a source file called β€œlanguages.go” for the package β€œlang” at the location “waytoeasylearn.com/ashok/golang/lang” in the GOPATH.

Since the β€œlanguages.go” belongs to the folder β€œlang”, the package name will be named β€œlang”. All files created inside the lib folder belongs to lang package.

package lang

var languages map[string]string

func init(){
	languages= make(map[string]string)
	languages["ja"] = "Java"
	languages["js"] = "JavaScript"
	languages["rb"] = "Ruby"
	languages["go"] = "Golang"
	languages["py"] = "Python"
}

func Get(key string) (string){
	return languages[key]
}

func Add(key,value string){
	 languages[key]=value
}

func GetAll() (map[string]string){
	return languages
}

In the above program, we included an init() method, so that this method will be invoked at the beginning of execution.

Let’s build our Go package for reusing with other packages. In the terminal window, go to the location lang folder, and run the following command.

$ go install

The go install command will build the package β€œlang” which will be available at the pkg sub directory of GOPATH.

Let’s create a β€œmain.go” for making an executable program where we want to reuse the code specified in the package β€œlang”.

package main

import (
	"fmt"

	"waytoeasylearn.com/ashok/golang/lang"
)

func main() {
	lang.Add("cpp", "C++")
	fmt.Println(lang.Get("cpp"))
	languages := lang.GetAll()
	for _, v := range languages {
		fmt.Println(v)
	}
}

In the above example, we import the lang package and call the exported methods provided by the lang package. The output of the above example looks like as follows

[email protected]:~/work/waytoeasylearn/golang$ go run main.go

Java
JavaScript
Ruby
Golang
Python
C++

That’s pretty much it. Awesome !! You just have created your first package.

How can we share this with other devs to use it?

Create to a repository on GitHub, push the code there and you are good to go. To use it in your project use,

go get github.com/waytoeasylearn/golang/lang
Creating and Reusing Packages


Scroll to top