Pankaj Bagwan
Pankaj Bagwan
1 min read



Go is modern language, so it has to take care of current software development practices; code reuse or DRY (Don’t Repeat Yourself) being one of them. In go code can be packed into modules and shipped. Lets look into how go uses packages.

Importing a Packages

A go package can be imported using import command, like we see in daily uses.

//importing one file
import "xyz"

//importing multiple packages at once

Creating a Package

To create a package, first we need to create a folder somewhere under our GO_PATH/src directory with the same name as package, that we want to declare. Let us create a math package under

#first cd into it
cd $GO_PATH/src/

#create a folder with same name as our package
mkdir math
cd math
touch math.go

Now open this file math.go and create an Avarage method

package math

func Average(elem []int64) int64 {
  total := int64(0)
  for _, x := range elem {
    total += x
  return total / int64(len(elem))

Note method name starts from capital letter, in Go, only methods, whose name starting from capital letter are imported, not others.

Now to make it package, we need to install it. run go install in math directory. This will create a math.a file under $GO_PATH/pkg/; verify same.

Now cd to $GO_PATH/src/ and create a pack.go to use this package

package main


func main() {
  arr := []int64{8,6,4,2}
  average := math.Average(arr)

That’s it.

About The Author

I am Pankaj Baagwan, a System Design Architect. A Computer Scientist by heart, process enthusiast, and open source author/contributor/writer. Advocates Karma. Love working with cutting edge, fascinating, open source technologies.

  • To consult Pankaj Bagwan on System Design, Cyber Security and Application Development, SEO and SMO, please reach out at me[at]bagwanpankaj[dot]com

  • For promotion/advertisement of your services and products on this blog, please reach out at me[at]bagwanpankaj[dot]com

Stay tuned <3. Signing off for RAAM