The Analogy: The Shop With a Counter
Walk into a shop and there are two worlds separated by a counter. On the customer side, everything is on shelves, labelled, arranged to be picked up: that is your exported surface. Behind the counter is the stockroom -- half-unpacked boxes, the returns pile, the kettle -- and it is not that customers are forbidden from it so much as that the building is shaped so they simply cannot reach it. In Go the counter is a single rule with no keyword attached to it: an identifier whose first rune is upper case is on the shelves; anything else is in the stockroom.
The rule applies at every level, and that surprises people. Account can be exported while its pence field is not, so no code outside the package can set a balance without going through your method. A method can be unexported on an exported type. A field of an exported struct can be unexported even though the struct itself is handed out freely. There is no public, no private, no protected; there is the case of one letter, checked by the compiler.
The critical detail is what the counter encloses. It is not the type and it is not the file -- it is the directory. Every .go file in one directory forms one package, and they can all touch each other's unexported identifiers freely. That is why splitting a 900-line package into six files costs you nothing at all, and why splitting it into six packages costs you a great deal: only the second kind of split creates counters you then have to build doors through.
Where the analogy runs out: shops can owe each other money in a loop, but packages cannot import each other in a loop. An import cycle is a compile error, not a runtime problem to be managed, and Go made that choice deliberately -- it is a large part of why the compiler is fast. There is also no "friend" access. The one escape hatch is a directory literally named internal, whose contents the compiler allows only packages under its parent to import.
Syntax or Core Structure
A three-package module. The tree first, because in Go the directory layout is the API:
myapp/
go.mod module example.com/myapp
main.go package main
ledger/
ledger.go package ledger
format.go package ledger (same package, second file)
internal/
audit/audit.go package audit (importable only inside myapp)
// ledger/ledger.go
// Package ledger records money movements in minor units (pence).
package ledger
import (
"errors"
"fmt"
)
// ErrOverdraft is returned when a movement would take the balance below zero.
var ErrOverdraft = errors.New("overdraft")
// Account is exported; pence and history are not, so no caller outside this
// package can change a balance except through Post.
type Account struct {
Name string
pence int64
history []string
}
func New(name string, openingPence int64) *Account {
return &Account{Name: name, pence: openingPence}
}
func (a *Account) Post(what string, delta int64) error {
if a.pence+delta < 0 {
return fmt.Errorf("post %s: %w", what, ErrOverdraft)
}
a.pence += delta
a.history = append(a.history, fmt.Sprintf("%-8s %+d", what, delta))
return nil
}
// Balance calls format, which lives in the other file of this package.
func (a *Account) Balance() string { return format(a.pence) }
func (a *Account) History() []string {
out := make([]string, len(a.history))
copy(out, a.history) // never hand a caller the internal slice
return out
}
// ledger/format.go
package ledger
import "fmt"
// format is unexported, yet every file in this directory can call it.
func format(pence int64) string {
sign := ""
if pence < 0 {
sign, pence = "-", -pence
}
return fmt.Sprintf("%s%d.%02d", sign, pence/100, pence%100)
}
// internal/audit/audit.go
// Package audit is importable only by packages under example.com/myapp.
package audit
var entries []string
func Log(verb, what string) { entries = append(entries, verb+" "+what) }
func Count() int { return len(entries) }
// main.go
package main
import (
"errors"
"fmt"
"example.com/myapp/internal/audit"
"example.com/myapp/ledger"
)
func main() {
a := ledger.New("ada", 1000)
// a.pence = 0 // will not compile: unexported field of another package
movements := []struct {
what string
delta int64
}{
{"salary", 25000},
{"rent", -18000},
{"coffee", -350},
{"holiday", -99000},
}
for _, m := range movements {
if err := a.Post(m.what, m.delta); err != nil {
audit.Log("rejected", m.what)
fmt.Println("rejected:", err, "| overdraft:", errors.Is(err, ledger.ErrOverdraft))
continue
}
audit.Log("posted", m.what)
}
fmt.Println("balance:", a.Balance())
for _, line := range a.History() {
fmt.Printf(" %s\n", line)
}
fmt.Println("audit:", audit.Count(), "entries")
}
Output:
rejected: post holiday: overdraft | overdraft: true
balance: 76.50
salary +25000
rent -18000
coffee -350
audit: 4 entries
Two things worth naming. format is invisible to main yet freely callable from ledger.go -- the file boundary means nothing, the directory boundary means everything. And audit is honest about a real smell: it keeps its state in a package-level var, which is acceptable in twenty lines of demo and a liability in a real system, because it cannot be reset between tests and cannot be used twice with different destinations. The fix is always the same shape -- an exported Recorder type with methods, created in main.
Technical Depth: Where the Boundaries Actually Are
The counter, level by level
| Declaration | Exported form | Effect of lower case |
|---|---|---|
| Type | type Account struct | Callers cannot name the type, though they can still hold values of it |
| Struct field | Name string | Invisible to other packages; also skipped by encoding/json and reflect |
| Method | func (a *Account) Post | Callable only inside the package; cannot satisfy an external interface |
| Function, var, const | func New, var ErrOverdraft | Package-local |
| Interface method | Notify(...) | An unexported method makes the interface unimplementable elsewhere |
That last row is a real technique: an interface with one unexported method can only be satisfied by types in your own package, which is how the standard library builds closed sets of implementations.
One directory, one package
Every file in a directory must declare the same package name, with one exception: package foo_test files, which live alongside package foo and see only its exported surface -- a way to test your API as a stranger would. File names are otherwise invisible to the compiler, with two exceptions that matter. Suffixes such as _linux.go, _windows.go and _amd64.go are implicit build constraints, and //go:build lines are explicit ones; either way an excluded file is not merely skipped at link time, it is not part of the package at all, so it cannot break the build on other platforms.
Initialization order, exactly
It is not top to bottom. The order is:
- Every imported package is initialized completely first, recursively, and each package exactly once no matter how many others import it.
- Package-level variables are initialized in dependency order: given
var a = b + 1andvar b = seed(),bruns first regardless of which line comes first. Independent variables go in declaration order, with files taken in sorted filename order. - All
init()functions run, in the same file order. A file may declare several; you cannot call them, reference them, or rely on them across packages beyond the guarantee above. main.mainstarts.
The practical consequence is that init() is the wrong place for anything that can fail, take time, or need configuration -- it runs before flag.Parse, before any config is read, and even when the only reason your package was linked in was one unrelated constant.
Import cycles and the two ways out
catalog -> notify -> catalog import cycle not allowed
There are exactly two honest fixes. Extract: pull the shared types into a third, dependency-free package that both import. Invert: have the consumer declare the interface it needs and let the other package satisfy it accidentally, wiring the two together in main. Inversion is almost always better, because it leaves you with a one-method interface instead of a new package, and Go's structural interfaces mean the satisfying package never imports the declaring one. Moving files around to make the error go away without changing the direction of a dependency just relocates the cycle.
The internal rule
| Directory | Importable by |
|---|---|
example.com/m/internal/audit | any package under example.com/m |
example.com/m/api/internal/codec | any package under example.com/m/api |
example.com/m/internal/... from another module | nobody -- compile error |
The compiler enforces this from directory position alone; there is nothing to configure. It is the right tool for code that several of your packages share but that you refuse to support as public API.
Naming: the call site is the documentation
A package name is a prefix the reader sees on every use, so it is chosen to read well there. ledger.New, not ledger.NewLedger. bytes.Buffer, not bytes.BytesBuffer. Short, lower case, one word, no underscores, no plurals. Packages named util, common, helpers, base or models describe nothing, attract everything, and become the cycle at the centre of your graph.
The package name is usually the last element of the import path but need not be: gopkg.in/yaml.v3 is package yaml, math/rand is rand. Where two imports collide, alias one at the import site. Two special import forms exist: _ "net/http/pprof" imports purely for the registration side effects of init, and the dot import . "fmt" dumps a package into your file scope -- legal, and almost never right.
Real World Example: Breaking a Cycle by Inverting It
The stock system wants to send a notice when an item runs low. The obvious layout has catalog calling notify, and notify importing catalog to read an Item -- a cycle. Here it is inverted: catalog declares the one-method interface it needs, notify satisfies it without ever naming it, and only main knows both exist.
shop/
go.mod module example.com/shop
catalog/catalog.go imports: fmt, sort (nothing of ours)
notify/notify.go imports: fmt (nothing of ours)
cmd/shop/main.go imports: catalog, notify
// catalog/catalog.go
// Package catalog owns the Item type and the rules for moving stock.
package catalog
import (
"fmt"
"sort"
)
type Item struct {
SKU string
Stock int
}
// Notifier is declared by the consumer and satisfied elsewhere.
// This single declaration is what removes the cycle.
type Notifier interface {
Notify(event, sku string, stock int)
}
type Catalog struct {
items map[string]*Item
n Notifier
}
// New accepts an interface and returns a concrete type.
func New(n Notifier, items ...Item) *Catalog {
c := &Catalog{items: make(map[string]*Item, len(items)), n: n}
for i := range items {
it := items[i] // fresh variable per iteration, so &it is distinct
c.items[it.SKU] = &it
}
return c
}
func (c *Catalog) Take(sku string, qty int) error {
it, ok := c.items[sku]
if !ok {
return fmt.Errorf("take %s: unknown sku", sku)
}
if it.Stock < qty {
return fmt.Errorf("take %s: only %d left", sku, it.Stock)
}
it.Stock -= qty
switch {
case it.Stock == 0:
c.emit("out-of-stock", it)
case it.Stock < 3:
c.emit("low-stock", it)
}
return nil
}
// emit is unexported, so the nil check exists in exactly one place.
func (c *Catalog) emit(event string, it *Item) {
if c.n == nil {
return
}
c.n.Notify(event, it.SKU, it.Stock)
}
func (c *Catalog) Report() []string {
out := make([]string, 0, len(c.items))
for _, it := range c.items {
out = append(out, fmt.Sprintf("%-6s %2d", it.SKU, it.Stock))
}
sort.Strings(out) // map iteration is random; sort before printing
return out
}
// notify/notify.go
// Package notify renders stock events. It imports no package of ours.
package notify
import "fmt"
type Collector struct{ Lines []string }
// Notify happens to match catalog.Notifier without naming it.
func (c *Collector) Notify(event, sku string, stock int) {
c.Lines = append(c.Lines, fmt.Sprintf("[%s] %s stock=%d", event, sku, stock))
}
// cmd/shop/main.go
package main
import (
"fmt"
"example.com/shop/catalog"
"example.com/shop/notify"
)
func main() {
col := ¬ify.Collector{}
c := catalog.New(col,
catalog.Item{SKU: "kb-01", Stock: 4},
catalog.Item{SKU: "ms-02", Stock: 2},
catalog.Item{SKU: "hp-03", Stock: 1},
)
orders := []struct {
sku string
qty int
}{
{"kb-01", 2},
{"ms-02", 2},
{"hp-03", 5},
{"zz-99", 1},
}
for _, o := range orders {
if err := c.Take(o.sku, o.qty); err != nil {
fmt.Println("error:", err)
}
}
fmt.Println("-- stock --")
for _, line := range c.Report() {
fmt.Println(line)
}
fmt.Println("-- events --")
for _, line := range col.Lines {
fmt.Println(line)
}
}
Output:
error: take hp-03: only 1 left
error: take zz-99: unknown sku
-- stock --
hp-03 1
kb-01 2
ms-02 0
-- events --
[low-stock] kb-01 stock=2
[out-of-stock] ms-02 stock=0
Look at the import lists in the tree and the shape of the program is already clear: catalog and notify are leaves that know nothing of each other, and cmd/shop is the only place where the two names appear together. That is the shape almost every healthy Go program has -- a wide, shallow tree with the wiring at the root and no first-party imports at the leaves. It is also why the cycle never had to be "managed": inverting one dependency removed it structurally.
The inverted interface is one method wide, and that is not an accident. catalog needs to say "something happened"; it does not need a notifier's configuration, retry policy, or template engine, so Notifier describes exactly the call it makes and nothing more. This is the concrete meaning of "accept interfaces, return structs": New takes the narrowest possible interface and hands back *Catalog, so callers get every method without needing a second interface to describe it.
The exported surface is Item, Notifier, Catalog, New, Take and Report -- six names, each of which is a promise. emit stayed lower case, which is why the c.n == nil check appears once instead of at all three call sites, and why a later change to batch events touches one function. Every identifier you decline to export is a decision you keep the right to reverse.
Report copies into a fresh slice and sorts before returning, for two separate reasons that are easy to conflate. The copy is about ownership: returning the internal slice would let a caller reorder your data. The sort is about determinism: Go randomises map iteration deliberately, so any output derived from a map must be ordered before it is printed or compared, or your tests will pass four times out of five. If notify ever did need to render an Item in full, the temptation to import catalog is exactly the cycle coming back -- pass the fields, or move Item into a third leaf package.
Common Mistakes
- Naming a package
util,common,helpersormodels. Such a name states no responsibility, so everything drifts into it, and because everything imports it, it becomes the node your next import cycle runs through. Name packages for what they provide. - Stutter at the call site.
ledger.LedgerAccount,ledger.NewLedger,http.HTTPServer. The package name is already there when the reader gets to yours; writeledger.Accountandledger.New. - One package per type. Directory explosion buys nothing -- Go's unit of encapsulation is the package, so a type in its own package can only collaborate with its neighbours through exported API. Many files, few packages.
- Exporting a field just to make a test compile. A test file in the same package sees every unexported identifier. Put the white-box test in
package ledgerand the API test inpackage ledger_test. - Shuffling files to silence an import cycle. The error is telling you a dependency points the wrong way. Extract the shared types or invert with an interface; relocating code moves the cycle without fixing it.
- Real work inside
init(). It runs beforeflag.Parse, cannot report an error except by panicking, cannot be skipped, and runs even when your package was linked in for one constant. Use an exported constructor called frommain. - Package-level mutable state. A shared
varcannot be reset between tests, cannot be pointed at two destinations, and turns every function into a method on invisible global data. Make a type. - Believing files are a boundary. Two files in one directory see all of each other's unexported identifiers. Only a new directory creates a counter.
- Dot imports.
import . "fmt"removes the qualifier that tells the reader where an identifier came from, and any new export in that package can silently shadow one of yours. - Returning the internal slice or map.
func (a *Account) History() []string { return a.history }publishes a live handle to your state; the caller can reorder or overwrite it. Copy on the way out. - Assuming the package name equals the last path element. It usually does but is not required, so
import "gopkg.in/yaml.v3"gives youyaml, and only the file'spackageclause is authoritative.
Best Practices
- Choose the package name by reading a call site out loud:
ledger.Post,catalog.Take. If the prefix repeats the identifier, rename one of them. - Start every identifier unexported and promote it when a caller genuinely needs it. Un-exporting later is a breaking change; exporting later is free.
- Declare the interface in the package that consumes it, sized to the calls that package actually makes -- one or two methods, not a mirror of some implementation.
- Split by responsibility into more files, and reach for a new package only when you want a real boundary with a deliberate door in it.
- Put shared-but-not-public code under
internal/, where the compiler enforces the boundary for you and no external module can depend on it. - Give the package one doc comment beginning
Package name ..., and a comment on every exported identifier; move a long overview intodoc.go. - Return copies of slices and maps from accessors, and sort anything derived from a map before printing or comparing it.
- Do the wiring in
mainorcmd/...: construct the concrete types there, pass them down as interfaces, and keep libraries free of globals andinitside effects.
Practice Exercises
- Build a two-file package. Create
temp/withtemp.go(an exportedReadingtype with an unexportedmilli intfield, plusNewandString) andconvert.go(unexportedtoFandtoChelpers). Prove frommainthattoFis unreachable and thatReading.Stringworks anyway. - Create and hit the internal wall. Add
internal/idgento your module, use it from two packages, then create a second module in a sibling directory and confirm the compiler refuses the import. Record the exact error message. - Cause an import cycle, then invert it. Write
storeandreportwhere each imports the other, read the compiler's cycle message, then fix it by declaring a one-method interface instoreand wiring both inmain. Note what the import lists look like before and after. - Audit an exported surface. Take the
ledgerpackage above, addDeposit,Withdrawand aStatementtype, then justify every capital letter in one sentence each. Demote anything you cannot justify and confirm the package still builds.