Creating and Reusing Packages
In this tutorial, we are going to discuss creating and reusing packages in the Go language.
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 to invoke this method 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 subdirectory 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
ashok@waytoeasylearn:~/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
That’s all about the Creating and Reusing Packages in Go language. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Go language.!!