Let’s Go, Everything you need to know about go packages

Supun Muthutantrige
2 min readApr 9, 2019

--

Detailed overview on go package structure

PART I

Go is build upon the DRY (Don’t Repeat Yourself) principal, with the mission to facilitate clean code. Functions are the basis which allows code reuse, next is Packages. Packages organize related files into modular units, which allows re-usability.

Packages in Go

A package is nothing but a collection of go source files. Every go source file should belong to a specific package. A go source file in a package could be either public or package private. Packages in a way reduce the compilation time, by recompiling only the changed source files.

main package

This is the main entry package, which starts the application. Programs which needs to be executable, should have a main package. If there is a main package in your application, go install will create a binary executable

“go install” by default will search your application in $GOPATH and in /home/go locations. If not found in either places, will throw an error.

├── bin
| └── app (binary executable generated from main package)
├── pkg
└── src
├── app
└── application.go (package main)
└── print
└── text.go (package print)

Similarly, if there is no main package in your application, go install will generate a package archive.

├── bin
├── pkg
| └── app.a
| └── print.a
└── src
├── app
└── application.go (package app)
└── print
└── text.go (package print)

“fmt” is a package archive (fmt.a). Used as a shared library, which doesn’t contain a main package.

Main package contains the main() function which is the entry point for the executable program. Similarly, you can name any function main() outside main package and these functions will act just as other functions.

In Go, a variable/type/function which start with a Capital letter is visible outside the package and can be accessed after importing the package from anywhere. Anything that doesn’t start with a capital letter is package private.

All import paths in a go source file should be relative to the src directory. Package Alias allow resolving conflicts for packages with the same name.

package mainimport (
"fmt",
strNumRed "/example/numb/red"
strWordRed "/example/word/red"
)
...

Next Section — Creating Go REST Apis Part I

--

--