Skip to content

Packages

Every Go program is made up of packages. When importing packages into a file, it is proper to use factored import statements, meaning combining all of the imports within parenthesis. The main package symbolizes code that will be run as a binary. Otherwise the package is a library.

Only names starting with Capital letters are exported from a package (public). Lowercase names will remain private within the package.

go
package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Printf("Now you have %g problems.\n", math.Sqrt(7))
}

Projects

Projects can be broken up into subpackages so they can be imported separately. The internal directoy can not be imported by someone using your package. Binaries should be kept in the cmd folder. Within cmd all files and any other binary files should include package main. In subpackages like auth, token, hash, and trace should have their respective package names.

project-root-directory/
  go.mod
  modname.go
  modname_test.go
  auth/
    auth.go
    auth_test.go
    token/
      token.go
      token_test.go
  hash/
    hash.go
  internal/
    trace/
      trace.go
  cmd/
    prog1/
      main.go
    prog2/
      main.go

go.mod includes the module name or where the code is located. For example, if the code is kept at github.com/someuser/modname, then the file should include:

module github.com/someuser/modname

In the importing code:

go
import "github.com/someuser/modname"
import "github.com/someuser/modname/auth"
import "github.com/someuser/modname/auth/token"
import "github.com/someuser/modname/hash"

To install the binaries:

bash
$ go install github.com/someuser/modname/prog1@latest
$ go install github.com/someuser/modname/prog2@latest