Skip to content
Tutorials Center
My learning

Topics

Lesson 94 of 147 ยท Modules and Packages

Packages and Visibility

Learn how Go packages work - package versus directory, exported and unexported names, imports and aliases, init order, internal packages and naming.

Every Go file starts with a package line, and every program you have written so far used package main and imported others like fmt and strings. A package is Go's unit of code organization and of encapsulation: a set of source files that are compiled together and share one namespace. Packages are how you split a growing program into understandable pieces, how you decide which parts other code may use, and how the whole standard library is structured.

This lesson explains what a package is, how Go decides what is visible outside of it, how imports work (including aliases, dot imports and blank imports), in which order package-level variables and init functions run, how internal directories restrict access, and how to name and design packages well. The next lessons build on this: Go Modules group packages into versioned units, and Project Layout shows how to arrange real projects.

Because the code editors on this site compile a single main.go file, multi-package examples appear as read-only code blocks, with a comment naming each file. The runnable examples demonstrate the rules with the standard library and with tools such as go/parser.

Packages and directories

A package is a directory of .go files that all declare the same package name. The compiler treats those files as one unit: a function declared in a.go can call one declared in b.go without any import, and names declared at package level must be unique across all files.

TEXT
shapes/
โ”œโ”€โ”€ shape.go      package shapes
โ”œโ”€โ”€ circle.go     package shapes
โ”œโ”€โ”€ rect.go       package shapes
โ””โ”€โ”€ rect_test.go  package shapes   (tests may use package shapes_test)

A few rules follow directly:

  • One directory, one package (plus an optional external test package named <name>_test). You cannot mix package shapes and package geometry in the same directory.
  • The package name is what you write in code (shapes.Circle). The import path is what you write in the import statement ("example.com/geo/shapes"). By convention the last element of the import path equals the package name, but nothing forces it.
  • package main is special. It produces an executable, and it must contain func main(). Every other package is a library: it can be imported but not run.
  • Files are not packages. Splitting a 2,000-line file into four files of the same package changes nothing for the compiler; splitting it into four packages changes who can see what.

Order does not matter between files or declarations. You can use a function before its declaration in the same package, which is why Go has no header files or forward declarations.

Exported and unexported names

Go has no public, private or protected keywords. Visibility is decided by the first character of the name:

  • If it is an uppercase letter, the name is exported: other packages can use it.
  • Otherwise (lowercase letter, _, or anything without case) it is unexported: usable only inside its own package.

This applies to every kind of identifier: functions, types, constants, variables, struct fields and methods. You do not mark the thing; you just name it. The rule is checked by the compiler, and the standard library even exposes it as token.IsExported:

Go What counts as exported

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

There are some details worth remembering:

  • The test is "starts with a Unicode uppercase letter", so รœnder is exported while รผber is not. Names in scripts without case, such as ไธ–็•Œ, are never exported. Use ASCII names for anything public.
  • _x is unexported. A single underscore _ is the blank identifier and not a name at all.
  • Reflection shows the same rule: only exported struct fields have IsExported() == true, and the method set of a type, as seen from another package, lists only exported methods (deposit is missing from the output).
  • Exported means "exported from the package", not from the file. Two files in the same package see each other's unexported names freely.
  • Encoders such as encoding/json rely on this rule: they ignore unexported fields, because code in another package could not set them either. A struct with all-lowercase fields marshals to {}, a very common beginner surprise (JSON covers it).

Encapsulation by convention

Because the granularity of privacy is the package, Go programs typically hide representation and expose behavior: unexported fields, exported constructors and methods.

Go
// file: bank/account.go
package bank

import "errors"

var ErrInsufficientFunds = errors.New("bank: insufficient funds")

type Account struct {
	owner   string  // unexported: only package bank can touch these
	balance float64
}

func NewAccount(owner string) *Account { return &Account{owner: owner} }

func (a *Account) Balance() float64 { return a.balance }

func (a *Account) Withdraw(x float64) error {
	if x > a.balance {
		return ErrInsufficientFunds
	}
	a.balance -= x
	return nil
}

From another package, bank.Account{balance: 1e9} does not compile ("unknown field balance"), so code outside can never put an account into an invalid state. Everyone must go through NewAccount, Deposit, Withdraw and so on, where the invariants are enforced. See Constructors, Options and Builders for the patterns that come with this.

The compiler enforces it

Using an unexported name from another package is a compile error. The error message even suggests the exported name if you got the case wrong:

Go Using an unexported name (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler reports ./main.go:9:17: undefined: strings.builder (but have Builder). From outside the package an unexported name simply does not exist. Another everyday compile error, discussed next, is unused imports.

Imports

import makes another package's exported names available through the package name. A group in parentheses is the standard style, and gofmt sorts it:

Go
import (
	"fmt"
	"math/rand/v2"

	"example.com/geo/shapes"
)

The standard library comes first, then a blank line, then third-party and your own packages. The name you use in code is the package's declared name, which for "math/rand/v2" is rand (a trailing version element is not part of the name).

Go is strict about two things: you cannot import a package you do not use, and you cannot declare an unused local variable. Both are compile errors, because unused imports slow builds and clutter code:

Go An unused import (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler stops with ./main.go:5:2: "os" imported and not used. Editors and the goimports tool add and remove imports for you, so you rarely manage them by hand.

Import aliases

Two packages can have the same name: math/rand and crypto/rand are both rand. Give one an alias before the path. Aliases are also handy to shorten a long name or avoid shadowing a local variable:

Go Aliased imports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The seeded generator always prints the same two numbers, while crypto/rand fills the buffer with unpredictable bytes (we print only how many bytes it wrote). Use aliases sparingly; a good alias is short, lowercase and conventional (crand, pb for generated protobuf code, v1).

Dot and blank imports

Two special forms exist, and both are used rarely.

A dot import (import . "fmt") puts the package's exported names into your file's scope, so you write Println without fmt.. It makes code harder to read because you can no longer tell where a name comes from, and it can cause conflicts. Style guides advise against it, except in some test code.

A blank import (import _ "path") imports a package only for its side effects: its init functions run, and nothing is used by name. This is the mechanism behind database drivers (import _ "github.com/lib/pq"), image decoders (_ "image/png") and embedded time-zone data:

Go Dot and blank imports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

time/tzdata embeds the time-zone database into your binary, so time.LoadLocation works even on a machine without zone files. The blank import registers that data through its init function. The same pattern explains why a database program imports a driver it never refers to: the driver registers itself with database/sql when it is initialized. A misspelled or forgotten blank import is a classic reason for the error "unknown driver".

Package initialization with side effects is powerful and easy to abuse. Prefer explicit registration (Register() functions, constructors that take a dependency) in your own packages. Reserve blank imports for the few cases where an ecosystem convention requires them.

Initialization order

Before main runs, Go initializes the program one package at a time, dependencies first. Inside each package the sequence is:

  1. Package-level variables are initialized in dependency order: a variable is initialized only after the variables it refers to. Where there is no dependency, declaration order wins.
  2. Then every init function runs, in the order in which they appear in the files, with files presented to the compiler sorted by file name. A package may have several init functions, even in one file; they cannot be called or referenced.
  3. Finally main.main runs, for package main.

An imported package is initialized only once, no matter how many packages import it, and importing is not allowed to create a cycle.

Go Variable and init order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

a is declared first, but it depends on b and c, so those are initialized first, b before c because that is their declaration order. Both call f, which depends on d, so d is initialized (to 3) before either call. That is why the first call prints 4 and the second 5, and a becomes 9. Only after all variables are ready do the two init functions run, in order, before main.

Keep init functions small and predictable: validate a static table, register a codec, set a default. Do not read the network, files or the environment in init, because that makes a program hard to test and a failure in a library impossible to handle. Put that work into explicit functions the caller invokes.

Seeing packages like the compiler does

Tools such as gofmt, go vet and gopls read your code with the standard library packages go/parser and go/ast. The next program parses two in-memory files of one package and prints the package name, the imports and which top-level names are exported. It is a faithful miniature of what the go tool does when it collects a package's files:

Go Reading a package with go/parser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Files are processed in sorted order (the go tool also sorts them, which is why init order across files is by file name), both declare package shapes, and each has its own import list: imports are per file, not per package. If rect.go imports strings, shape.go does not automatically get it. The tool lists methods as func declarations; their exported-ness depends on the method name, so String and Area are exported while helper is not.

Internal packages

Exported names are visible to everyone who imports the package. That is a problem if you want to share code between your own packages without promising it to the world. Go solves this with a special directory name: a package under a directory called internal can be imported only by code inside the parent of that internal directory.

TEXT
example.com/shop/
โ”œโ”€โ”€ go.mod
โ”œโ”€โ”€ cmd/
โ”‚   โ””โ”€โ”€ shopd/main.go              imports example.com/shop/internal/orders   OK
โ”œโ”€โ”€ internal/
โ”‚   โ”œโ”€โ”€ orders/orders.go           importable only from inside example.com/shop/...
โ”‚   โ””โ”€โ”€ db/db.go
โ””โ”€โ”€ api/handlers.go                imports example.com/shop/internal/db       OK
Go
// file: other-module/main.go
package main

import "example.com/shop/internal/orders" // compile error: use of internal package not allowed

func main() { orders.Place() }

The compiler rejects the import from anywhere outside example.com/shop/.... This is the most important tool for keeping an API small: you can restructure anything in internal without breaking users, because they never could import it. Libraries that you publish to others should keep implementation details in internal; applications often put almost everything there.

Designing and naming packages

Good packages are small, focused and named for what they provide. A few conventions are used throughout the Go community:

  • Names are short, lowercase, single words with no underscores or camelCase: bytes, http, orders. Avoid vague names such as util, common, helpers and misc. A package called util becomes a dumping ground, and callers read util.Do() without knowing what it does.
  • The name is part of every identifier's meaning. Callers write http.Client, bytes.Buffer and strings.Builder, so skip the stutter: http.HTTPClient and orders.OrderService repeat themselves. Prefer orders.Service or orders.Place.
  • Don't name a package after what it contains: not models, types or interfaces. Group by what the code does (billing, auth), not by what kind of declaration it holds.
  • Avoid import cycles. If a imports b, then b cannot import a. The compiler reports "import cycle not allowed". Break a cycle by moving the shared types into a third package, or by defining a small interface in the package that needs the behavior (Designing with Interfaces explains why the consumer should own the interface).
  • Export as little as possible. Every exported name is a promise. Start unexported, and export when another package truly needs it.
  • A package comment (// Package orders implements ...) before the package clause becomes the first line in documentation; see Comments and Documentation.

Package names do not have to be unique across the world, because an import path identifies the package. Two different libraries can both be called log. Inside one file, though, an alias is required when both are imported.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these identifiers is exported from its package?

    An identifier is exported when its first character is a Unicode uppercase letter. A leading underscore, a lowercase letter, or a character from a script without case does not qualify.
  2. 2. What happens when you compile a file that imports "os" but never uses it?

    Go refuses to compile files with unused imports. Remove the import, or use a blank import (import _ "os") if you only want its side effects.
  3. 3. Package-level variables var x = y + 1 and var y = 2 are declared in that order. What is x?

    Go initializes package-level variables in dependency order, not source order. y is initialized first, then x becomes 3.
  4. 4. What does import _ "time/tzdata" do?

    A blank import runs the package's init functions without making its names available. time/tzdata uses this to register embedded time-zone data.
  5. 5. A package lives at example.com/shop/internal/db. Which code may import it?

    The internal rule allows imports only from the tree rooted at the parent of the internal directory, here example.com/shop.

Summary

  • A package is a directory of files that share one package name and one namespace. package main builds a program; every other package is a library.
  • Visibility is decided by the first letter: an uppercase Unicode letter exports a name, anything else keeps it private to the package. Caseless scripts can never be exported.
  • Hide representation (unexported fields) and expose behavior (exported constructors and methods) to protect invariants.
  • Imports are per file, must all be used, and can be aliased (crand), dotted (., discouraged) or blank (_, for side effects such as driver registration).
  • Initialization runs imported packages first, then package variables in dependency order, then init functions, then main.
  • Packages under an internal directory can only be imported from the parent tree, which keeps implementation details private.
  • Name packages with short lowercase nouns, avoid util, avoid stutter (orders.Service), and avoid import cycles.

Next: Go Modules