The Story Tale of Go Packages

Ankit Kumar
2 min readOct 1, 2021

In this article, I will explain some of the interesting features of Go packages.

Why do we need a package in Go?

  1. In Go, every source file must belong to a package.
  2. Every function, type, and variable of a source file belongs to its declared package and can be accessed by other source files within the same package.
  3. The two types of go packages are utility packages(reusable helpers) and executable packages(holds executable file to build and run).
  4. You can access exported declared functions in the same package using the dot operator.
    One of the famous examples of this is :

One of such functions exported by fmt is Println() which formats and writes data to the standard output.

package main 
import "fmt"
func main() {
fmt.Println("Hello There")
}

Benefits of it?

It prevents name conflict, looks concise and code readability is good

How to Export from Packages?

It’s very simple as Go focus on Letter Case:

Any functions, types, or variables with a Capitalized Name are exported and Visible outside of a Package.

So what if the first letter is not Capital?

That type of functions, types, or variables are counted as private and which is not accessible out of packages.

package main
import "fmt"
const Str = "hello there!" //1st letter is capital, so accessible outsideconst str = "good bye" //not accessiblefunc Sum() {}func product() {}

Importing packages from remote modules

An import path can describe how to obtain the package source code using a revision control system such as Git or Mercurial. The go tool uses this property to automatically fetch packages from remote repositories.
package main

import (
“fmt”
“example/user/hello/morestrings”
“github.com/google/go-cmp/cmp”
)
func main() {
fmt.Println(morestrings.ReverseRunes(“!oG ,olleH”))
fmt.Println(cmp.Diff(“Hello World”, “Hello Go”))
}

Also, Now you have a dependency on external modules, you need to download that module and record its version in your go.mod file. The go mod tidy the command adds missing module requirements for imported packages and removes requirements on modules that aren't used anymore.

Read my articles on Go — Project Structure and Guidelines

That’s all for today, Have a good read and a nice day. 😃

References:

--

--