ZetCode

Go package

last modified October 30, 2026 Go 1.27

In this article we show how to work with packages in Go. A package is a collection of source files in one directory that share a name and form a single unit of compilation.

Every file starts with a package clause. Constants, types, variables and functions declared at the top level belong to the package and are visible in all of its files. Identifiers that start with a capital letter are exported and can be used by other packages; everything else stays private to the package.

Packages are organized into modules. The module path from go.mod is the prefix of the import path of every package inside the module, and a package in a subdirectory is imported as module path plus directory.

All examples in this article were compiled and run with Go 1.27.0.

Two files in one package

The files below form the main package of a module named com.zetcode/two. The constant and the function are declared in helpers.go and used in main.go without any import.

helpers.go
package main

import "fmt"

const version = "1.4"

func greet(name string) {
    fmt.Println("hello", name)
}

The names are not exported, and they do not need to be: both files are compiled as one package, so the visibility rules apply only across package boundaries.

main.go
package main

import "fmt"

func main() {

    greet("John")
    fmt.Println("version", version)
}

go run . builds the whole package, which means every .go file in the directory. Naming a single file, go run main.go, compiles only that file and fails with undefined: greet.

$ go mod init com.zetcode/two
$ go run .
hello John
version 1.4

The main package

The package named main is special: it is compiled into an executable, and its main function is the entry point. A package with any other name is compiled as a library and cannot be run directly.

$ go build -o two .
$ ./two
hello John
version 1.4

Building a library package with go build produces no binary; the command only checks that the package compiles. go install also places the result in GOBIN, which matters for a main package and has no visible effect for a library.

A custom package

A package in a subdirectory is imported by its full path. The module com.zetcode/demo below has a textutil directory, so the import path is com.zetcode/demo/textutil.

textutil/textutil.go
// Package textutil provides small text helpers.
package textutil

// Reverse returns the runes of s in the opposite order.
func Reverse(s string) string {

    r := []rune(s)

    for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
        r[i], r[j] = r[j], r[i]
    }

    return string(r)
}

func normalize(s string) string {
    return s
}

Reverse converts the string to runes first, so multibyte characters are reversed as whole characters and not as bytes. normalize is lowercase and therefore private to the package.

main.go
package main

import (
    "fmt"

    "com.zetcode/demo/textutil"
)

func main() {

    fmt.Println(textutil.Reverse("falcon"))
}

The last element of the import path is the package name, and the call uses that name as a qualifier. The import path itself never appears in the code after the import block.

$ go mod init com.zetcode/demo
$ go run .
noclaf

Unexported identifiers

Calling a lowercase name from another package is a compile error, not a run-time one. The compiler resolves every identifier before the program starts.

main.go
package main

import (
    "fmt"

    "com.zetcode/demo/textutil"
)

func main() {
    fmt.Println(textutil.normalize("x"))
}

The message names the qualified identifier. There is no reflection or unsafe trick involved, and no build tag changes the rule: the export decision is part of the package API.

$ go build main.go
# command-line-arguments
./main.go:10:23: undefined: textutil.normalize

Directory name and package name

The directory name and the package name do not have to match. The import path follows the directory, while the qualifier in the code follows the package clause.

strx/strx.go
package strtools

import "strings"

// JoinUpper joins the words with a dash and uppercases the result.
func JoinUpper(words []string) string {
    return strings.ToUpper(strings.Join(words, "-"))
}

The file sits in strx, so the import path ends with strx, but the identifier in front of the call is strtools.

main.go
package main

import (
    "fmt"

    "com.zetcode/demo/strx"
)

func main() {
    fmt.Println(strtools.JoinUpper([]string{"an", "old", "falcon"}))
}

The convention is to keep both names equal. A mismatch confuses readers, who see one name in the import block and another one in the code, and it breaks the assumption that the last path element identifies the package.

$ go run main.go
AN-OLD-FALCON

Package aliases

An import may declare a different name for the package. The alias replaces the package name in the file, which is useful for long names or for two packages with the same last path element.

main.go
package main

import (
    tx "com.zetcode/demo/textutil"
    "fmt"
)

func main() {

    langs := []string{"F#", "Go", "Python", "Perl"}

    fmt.Println(tx.Reverse("falcon"))
    fmt.Println(len(langs))
}

The alias tx is local to this file; other files of the same package still use textutil unless they declare their own alias. An import that is not used is a compile error, so aliases are never decorative.

$ go run main.go
noclaf
4

Blank imports and init functions

A blank import _ "path" runs the init function of the package without binding a name. This is how database drivers and plugin packages register themselves.

plugins/plugins.go
package plugins

var names []string

// Register adds a plugin name to the registry.
func Register(name string) {
    names = append(names, name)
}

// Names returns the registered plugin names.
func Names() []string {
    return names
}

The registry is a package-level slice. It starts empty and is filled by the init functions of the imported plugin packages.

plugins/csv/csv.go
package csv

import "com.zetcode/demo/plugins"

func init() {
    plugins.Register("csv")
}

The json package has an identical file that registers "json". Neither package exports anything; their only purpose is the side effect at startup.

main.go
package main

import (
    "fmt"

    "com.zetcode/demo/plugins"
    _ "com.zetcode/demo/plugins/csv"
    _ "com.zetcode/demo/plugins/json"
)

func main() {
    fmt.Println(plugins.Names())
}

The names appear in the order in which the plugin packages are initialized, which follows their order in the import block. Removing one of the blank imports removes its name from the slice.

$ go run main.go
[csv json]

Initialization order

Initialization happens before main and follows the import graph: imported packages first, then the importing package. Within a package, variables are initialized in declaration order and init functions run afterwards.

initdemo/alpha/alpha.go
package alpha

import "fmt"

var Value = "alpha"

func init() {
    fmt.Println("alpha init")
}

The beta package imports alpha and reads its exported variable from an init function, which proves that alpha was already initialized.

initdemo/beta/beta.go
package beta

import (
    "fmt"

    "com.zetcode/demo/initdemo/alpha"
)

func init() {
    fmt.Println("beta init, alpha.Value =", alpha.Value)
}

The main package prints from its own init and from main, which shows the last two steps of the sequence.

main.go
package main

import (
    "fmt"

    "com.zetcode/demo/initdemo/beta"
)

func init() {
    fmt.Println("main init")
}

func main() {
    fmt.Println("main body", beta.Greeting)
}

The beta package also declares the constant Greeting, so the import is used and the chain of initialization is complete.

$ go run main.go
alpha init
beta init, alpha.Value = alpha
main init
main body beta

Internal packages

A directory named internal restricts the import to code inside the tree rooted at the parent of internal. The compiler enforces the rule and reports the offending import.

internal/config/config.go
package config

const Name = "demo"

Code inside com.zetcode/demo can import com.zetcode/demo/internal/config. A separate module that replaces com.zetcode/demo with a local directory cannot.

main.go
package main

import (
    "fmt"

    "com.zetcode/demo/internal/config"
)

func main() {
    fmt.Println(config.Name)
}

The program was built in a module named example.com/outside that points at the demo module with a replace directive. The import path is correct, the file exists, and the failure is purely a visibility rule.

$ go build ./...
package example.com/outside
    main.go:6:2: use of internal package com.zetcode/demo/internal/config not allowed

Import cycles

Two packages may not import each other, directly or through a chain. The compiler reports the complete cycle, which makes the first step of the fix easy to find.

cycle/a/a.go
package a

import "com.zetcode/demo/cycle/b"

func A() string { return b.B() }

Package b returns the favour, and the build stops before any code is generated.

cycle/b/b.go
package b

import "com.zetcode/demo/cycle/a"

func B() string { return a.A() }

The usual fix is to move the shared types into a third package that both import, or to replace the call with a function value passed in from main.

$ go build ./cycle/...
package com.zetcode/demo/cycle/a
    imports com.zetcode/demo/cycle/b from a.go
    imports com.zetcode/demo/cycle/a from b.go: import cycle not allowed

Documentation

go doc prints the exported API of a package. A comment directly above the package clause becomes the package documentation, and a comment above a declaration becomes the documentation of that declaration.

$ go doc ./textutil
package textutil // import "com.zetcode/demo/textutil"

Package textutil provides small text helpers.

func Reverse(s string) string

The single function is listed because it is the only exported one; the unexported normalize does not appear. The same information is served by pkg.go.dev for published modules.

Source

The Go specification - packages

In this article we have created packages, exported and hidden identifiers, imported packages by module path, used aliases and blank imports, followed the initialization order, and seen the errors produced by internal packages and import cycles.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Go tutorials.