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.
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 github.com/go_to_go/pack_it
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/github.com/go_to_go/pack_it
; verify same.
Now cd
to $GO_PATH/src/github.com/go_to_go/pack_it
and create a pack.go
to use this package
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