SyntaxPilot
Courses/Go Programming/Lesson 27

Go Programming · Lesson 27 of 89 · 12 min

Packages

package clausepackage naming conventionsimport pathsexported and unexported identifiersimport aliasesblank importsdot importsinit functionspackage initialisation orderpackage-level variablesinternal packagesavoiding import cycles

These are the notes for Go episode 27. Until now every program fit in one file called main.go. Real programs don't. In this episode the chai shop's code grows until two helpers called price collide, and you invent the fix that every Go program is built from: packages. You will learn the package clause (package menu), how a folder becomes a package, and how an import path is built from the module path plus the folder. You will see one capital letter decide what other packages may use (exported vs unexported identifiers), follow Go's package naming conventions, fix a clash between two packages called rand with an import alias, load a package only for its side effects with a blank import, and see why dot imports are best avoided. You will watch Go set up package-level variables and run init functions in a fixed initialisation order before main, hide a secret recipe in an internal package, and break an import cycle. Single-file examples run as-is in the SyntaxPilot compiler (language: Go) with go run main.go. Multi-package examples need several folders, so they were run in a real module on a computer (go mod init example.com/shop, then go run .). All outputs and errors are from real runs (Go 1.24, linux/amd64).

The problem: one big file

Raju's chai shop program started small. Now main.go has a menu section, billing, stock and delivery: hundreds of lines. Months later someone adds a delivery charge and calls it price, without noticing that the menu section already has a price function:

package main

import "fmt"

// menu section
func price(item string) int {
    return map[string]int{"chai": 10, "samosa": 15}[item]
}

// delivery section, written months later
func price(km int) int {
    return 20 + 5*km
}

func main() {
    fmt.Println(price("chai"))
}
# command-line-arguments
./main.go:11:6: price redeclared in this block
    ./main.go:6:6: other declaration of price
  • Redeclared means the same name was declared twice in the same place. Go also tells you where the other declaration is (line 6).
  • Go has no function overloading (two functions with the same name but different parameters, as in Java or C++), so the different parameter types don't help.
  • Why it failed: everything in one package shares one namespace. A namespace is a space in which every name must be unique, like roll numbers in one class: two students can both be "Asha", but not both be roll number 12.
  • We could rename things forever (menuPrice, deliveryPrice, stockPrice...), but the file keeps growing and nobody can find anything. Better: give each part of the program its own room.

What is a package?

Think of a restaurant.

In a restaurant In Go Name
Rooms: kitchen, store room, counter. A knife in the kitchen and a knife in the store don't clash one folder of .go files compiled together, with its own namespace package
The sign on each door: "KITCHEN" the first line of every file: package menu package clause
The full address: shop + room example.com/shop/menu import path = module path + folder
  • A package is a folder of .go files that are compiled together and share one namespace. Names in different packages never clash: menu.Price and delivery.Price can both exist.
  • The package clause is the first statement of every Go file: the keyword package and a name. Every file in one folder must use the same package name. If they don't, the Go tool refuses (real output, with menu/extra.go saying package food):
main.go:6:5: found packages food (extra.go) and menu (menu.go) in /tmp/g/ns2x/menu
  • package main is special: it is the package that becomes a runnable program, and it must have func main() (episode 1). Every other package is a library package: code for other packages to use.
  • A module (episode 2) is a whole project: a folder tree with a go.mod file at the top. The module line in go.mod gives the module path, the project's name, usually written like a web address so it is unique worldwide (example.com/shop, github.com/you/shop).
  • The import path of a package is the module path plus the folder, separated by /: the folder menu inside module example.com/shop is imported as "example.com/shop/menu". Standard library packages have short paths with no domain: "fmt", "strings", "math/rand".

Your first package

Here is the real shop module. It was created with go mod init example.com/shop:

$ go mod init example.com/shop
go: creating new go.mod: module example.com/shop
shop/
├── go.mod          module example.com/shop
├── main.go         package main
└── menu/
    └── menu.go     package menu

go.mod:

module example.com/shop

go 1.24.7

menu/menu.go:

package menu

var Items = []string{"chai", "samosa"}

var discount = 2

func Price(item string) int {
    return prices[item] - discount
}

var prices = map[string]int{"chai": 12, "samosa": 17}
  • Package-level variables: Items, discount and prices are declared outside any function, at the top level of the package (the package block). Every function in the package can use them, in any file of the package, and they live for the whole run of the program. Notice that Price uses prices even though prices is declared below it: order doesn't matter at package level.
  • By convention the folder name and the package name are the same (menu/ holds package menu).
  • Look at the first letters: Items and Price are capitalised; discount and prices are not. That is the next section.

Exported vs unexported

main.go imports the package by its import path, then uses its names with the package name in front, like menu.Price. Let's also try to peek at menu.discount:

package main

import (
    "fmt"

    "example.com/shop/menu"
)

func main() {
    fmt.Println(menu.Price("chai"))
    fmt.Println(menu.Items)
    fmt.Println(menu.discount)
}
$ go run .
# example.com/shop
./main.go:12:22: name discount not exported by package menu
  • go run . builds and runs the package in the current folder (.), together with every package it imports from the module.
  • The qualified identifier menu.Price is a package name, a dot, and a name. Without the import, menu means nothing: ./main.go:6:17: undefined: menu (real output, from a main.go that forgot the import).
In a restaurant In Go
The counter: customers can use it exported names (Price, Items): start with a capital letter; usable from any package
The back kitchen: staff only unexported names (discount, prices): start with a small letter (or _); usable only inside their own package
  • That is the whole rule. Go has no public or private keywords: the first letter is the access control. The spec says a name is exported if its first character is a Unicode upper case letter (so Été is exported too) and it is declared in the package block, or it is a field or method name.
  • Hiding details behind a small public surface is called encapsulation. Because nothing outside menu can touch discount, the menu package can change it, rename it or delete it without breaking anyone.

Remove the discount line and run again:

package main

import (
    "fmt"

    "example.com/shop/menu"
)

func main() {
    fmt.Println(menu.Price("chai"))
    fmt.Println(menu.Items)
}
$ go run .
10
[chai samosa]

10 is chai at 12 minus the hidden discount of 2. main uses Price; Price uses discount inside its own package.

The same rule in the standard library

Struct fields and methods follow the same capital-letter rule (episode 19). strings.Builder (episode 17) has exported methods like WriteString and Len, and keeps its bytes in an unexported field called buf:

package main

import (
    "fmt"
    "strings"
)

// the same rule in the standard library

func main() {
    var b strings.Builder
    b.WriteString("chai ")
    b.WriteString("samosa")
    fmt.Println(b.String(), b.Len())
    fmt.Println(b.buf)
}
# command-line-arguments
./main.go:15:19: b.buf undefined (cannot refer to unexported field buf)

Nothing is printed at all: this is a compile error, so the program never ran. Delete the last line and it prints chai samosa 11.

Import aliases

A dice game needs math/rand (fast pseudo-random numbers). A one-time password (OTP) needs crypto/rand (secure random bytes that can't be guessed). Both packages are called rand: the package name is the one in the package clause, which by convention is the last element of the import path.

package main

import (
    "crypto/rand"
    "fmt"
    "math/rand"
)

// two packages, both named rand

func main() {
    fmt.Println(rand.Intn(100))
}
# command-line-arguments
./main.go:6:5: rand redeclared in this block
    ./main.go:4:5: other declaration of rand
./main.go:6:5: "math/rand" imported and not used
./main.go:12:22: undefined: rand.Intn

Two imports, one name in this file. The fix is an import alias: a different local name written before the path. It renames the package only in this file.

package main

import (
    crand "crypto/rand"
    "fmt"
    "math/rand"
    str "strings"
)

// an alias renames a package in this file

func main() {
    n := rand.Intn(6) + 1 // a dice roll
    fmt.Println("dice ok:", n >= 1 && n <= 6)

    otp := make([]byte, 3)
    crand.Read(otp) // secure random bytes
    fmt.Printf("OTP bytes: %d\n", len(otp))

    up := str.ToUpper("chai")
    fmt.Println(up)
}
dice ok: true
OTP bytes: 3
CHAI
  • rand.Intn(6) returns a pseudo-random number from 0 to 5; + 1 makes a dice roll (1 to 6). The program prints dice ok: true instead of the number so the output is the same on every run.
  • crand.Read(otp) fills the slice with secure random bytes.
  • str for strings works but is just for show: use aliases to fix a clash or a confusing name, not to save typing.

Naming packages

From the Go blog article "Package names" (go.dev/blog/package-names):

Rule Good Bad
short, clear, lower case, no under_scores or mixedCaps menu, billing, strconv Menu, menu_items, menuItems
don't repeat the package name in exported names: callers already write it http.Server, menu.Price http.HTTPServer, menu.MenuPrice
avoid meaningless names billing, recipe util, common, misc: they give "no sense of what the package contains"
folder name = package name (convention) menu/ → package menu menu/ → package food (allowed in a folder of its own, but confusing)
  • Repeating the package name in an exported name is called stutter: menu.MenuPrice says "menu" twice.

Blank imports

Every import must be used. An import you never use is a compile error (episode 3):

package main

import (
    "fmt"
    "strings"
)

// an import you don't use

func main() {
    fmt.Println("chai")
}
# command-line-arguments
./main.go:5:5: "strings" imported and not used

Usually that keeps code clean. But here is a case where you need a package you never call by name. The shop's logo is a tiny PNG image, stored as base64 text (a way to write any bytes using only letters, digits, + and /). image.DecodeConfig reads an image's format and size:

package main

import (
    "bytes"
    "encoding/base64"
    "fmt"
    "image"
)

const logo = "iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAAD0lEQVR4nGP4z8Dwn4EBAAj+Af9IxWaQAAAAAElFTkSuQmCC"

func main() {
    data, _ := base64.StdEncoding.DecodeString(logo)
    cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Println(format, cfg.Width, "x", cfg.Height)
}
error: image: unknown format

The image package knows no file formats by itself. The package image/png teaches it PNG, but it does that by running set-up code (an init function that calls image.RegisterFormat) when it is loaded. We never call anything from image/png by name. That is what a blank import is for: an underscore _ as the alias.

package main

import (
    "bytes"
    "encoding/base64"
    "fmt"
    "image"
    _ "image/png"
)

const logo = "iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAAD0lEQVR4nGP4z8Dwn4EBAAj+Af9IxWaQAAAAAElFTkSuQmCC"

func main() {
    data, _ := base64.StdEncoding.DecodeString(logo)
    cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
    if err != nil {
        fmt.Println("error:", err)
        return
    }
    fmt.Println(format, cfg.Width, "x", cfg.Height)
}
png 2 x 1
  • A side effect is something a package does just by being loaded (here: registering the PNG decoder), as opposed to something you call.
  • _ "path" loads the package and runs its initialisation, but gives you no name to use, so "imported and not used" can't happen.
  • Database drivers work the same way: a driver package calls sql.Register (from database/sql) in its init, so programs import it with _ and then open the database by the driver's name. Put blank imports in package main (or tests), so the program, not a library, decides which side effects it wants.

Dot imports

The opposite of a blank import: a dot import, . then the path, pours all of a package's exported names into your file, so you can use them without the package name:

package main

import . "fmt"

// a dot import pours names into this file

func main() {
    Println("no fmt. prefix")
    Printf("%d items\n", 2)
    Println(Sprint("Println from ", "which package?"))
}
no fmt. prefix
2 items
Println from which package?
  • It works, but a reader can no longer tell where Println or Sprint comes from, and names from two dot imports (or your own names) can clash.
  • Go's Code Review Comments say about the one special test case where it helps: "Except for this one case, do not use import . in your programs." That case is an external test package (package menu_test) that can't import a helper package without creating a cycle.

Package-level variables, init functions and initialisation order

Every morning the shop opens in a fixed order:

Opening the shop In Go
1. Suppliers deliver milk and tea leaves every imported package is fully initialised first
2. The stock sheet is filled in, in the order you need it package-level variables get their values, sorted by dependency
3. Light the stove: one-time set-up init functions run
4. Open the shutter main runs

An init function is func init() with no parameters and no results, declared at package level. Go calls it automatically; you can't call it yourself. A package can have many init functions, even in one file.

package main

import "fmt"

var total = subtotal + tax // uses two variables declared below
var subtotal = load("subtotal", 100)
var tax = load("tax", subtotal/20)

func load(name string, v int) int {
    fmt.Println("init var", name, "=", v)
    return v
}

func init() {
    fmt.Println("init() #1: total is", total)
}

func init() {
    fmt.Println("init() #2: open the shop")
}

func main() {
    fmt.Println("main: bill", total)
}
init var subtotal = 100
init var tax = 5
init() #1: total is 105
init() #2: open the shop
main: bill 105
  • total is written first but needs subtotal and tax, so Go initialises subtotal (100), then tax (100/20 = 5), then total (105). This is dependency order: a variable is initialised only after every variable it uses. Among variables that don't depend on each other, the order you wrote them is kept.
  • Then the init functions run in the order they appear, then main.
  • Initialisation means giving variables their first values and running set-up code before the program's real work starts.

Calling init yourself is an error, because the name init is not really declared (real output):

./main.go:10:5: undefined: init

Across packages and files

The Go specification says it precisely:

  • "The entire package is initialized by assigning initial values to all its package-level variables followed by calling all init functions in the order they appear in the source, possibly in multiple files, as presented to the compiler."
  • "If a package has imports, the imported packages are initialized before initializing the package itself. If multiple packages import a package, the imported package will be initialized only once."
  • Initialisation "happens in a single goroutine, sequentially, one package at a time."

A real module with three packages. stock imports milk; main imports both, and has init functions in two files, a.go and b.go:

milk/milk.go:

package milk

import "fmt"

var Litres = 20

func init() { fmt.Println("milk: init") }

stock/stock.go:

package stock

import (
    "fmt"

    "example.com/shop/milk"
)

var Cups = milk.Litres * 10

func init() { fmt.Println("stock: init, cups =", Cups) }

b.go:

package main

import "fmt"

func init() { fmt.Println("main: init in b.go") }

a.go:

package main

import (
    "fmt"

    "example.com/shop/milk"
    "example.com/shop/stock"
)

func init() { fmt.Println("main: init in a.go") }

func main() {
    fmt.Println("main: open with", stock.Cups, "cups and", milk.Litres, "litres")
}
$ go run .
milk: init
stock: init, cups = 200
main: init in a.go
main: init in b.go
main: open with 200 cups and 20 litres
$ go run b.go a.go
milk: init
stock: init, cups = 200
main: init in b.go
main: init in a.go
main: open with 200 cups and 20 litres
  • milk was initialised once, before stock and main, even though both import it.
  • go run . hands the files to the compiler sorted by name (a.go, then b.go); go run b.go a.go hands them in the order you typed. The init order of main's two files changed with it. So never rely on the order of init functions in different files.
  • Keep init small. Hidden start-up work (opening files, connecting to a database) is hard to test, slows every program and test that imports the package, and can't return an error. Prefer an explicit function like menu.Load() that returns an error.

internal packages

The menu needs the shop's secret masala recipe. Nobody else should use it. But an exported name is visible to every package that imports yours. Go has a special folder name for this: internal. A package whose path contains an internal element can be imported only by code in the folder that contains internal, and that folder's sub-folders.

shop/
├── main.go               package main
└── menu/
    ├── menu.go           package menu
    └── internal/
        └── recipe/
            └── recipe.go package recipe

menu/internal/recipe/recipe.go:

package recipe

// Masala is the secret chai masala mix.
const Masala = "ginger, cardamom, clove"

menu/menu.go (allowed: menu/ is the folder that contains internal/):

package menu

import "example.com/shop/menu/internal/recipe"

var Items = []string{"chai", "samosa"}

func Price(item string) int {
    return prices[item]
}

func Recipe() string { return "secret: " + recipe.Masala[:6] + "..." }

var prices = map[string]int{"chai": 10, "samosa": 15}

main.go tries to import the recipe directly:

package main

import (
    "fmt"

    "example.com/shop/menu"
    "example.com/shop/menu/internal/recipe"
)

func main() {
    fmt.Println(menu.Recipe())
    fmt.Println(recipe.Masala)
}
$ go run .
package example.com/shop
    main.go:7:5: use of internal package example.com/shop/menu/internal/recipe not allowed

Remove the recipe import and the recipe.Masala line, and main gets only what menu chooses to expose:

$ go run .
secret: ginger...
  • The Go tool (not the compiler) enforces this. The standard library itself uses it: its private helpers live in packages like internal/bytealg, which your code can't import.
  • A top-level shop/internal/... folder can be used by every package in the module, but by no other module. That makes it the usual place for code you don't want to promise to outside users.

Import cycles

billing totals a bill using menu.Price, so billing imports menu. Then someone adds a combo price to menu that calls billing.Total. Now menu imports billing too.

billing/billing.go:

package billing

import "example.com/shop/menu"

func Total(items []string) int {
    t := 0
    for _, it := range items {
        t += menu.Price(it)
    }
    return t
}

menu/menu.go:

package menu

import (
    "example.com/shop/billing"
    "example.com/shop/menu/internal/recipe"
)

var Items = []string{"chai", "samosa"}

func Price(item string) int {
    return prices[item]
}

func Recipe() string { return "secret: " + recipe.Masala[:6] + "..." }

func ComboPrice() int { return billing.Total(Items) - 5 }

var prices = map[string]int{"chai": 10, "samosa": 15}

main.go:

package main

import (
    "fmt"

    "example.com/shop/billing"
)

func main() {
    fmt.Println(billing.Total([]string{"chai", "samosa"}))
}
$ go run .
package example.com/shop
    imports example.com/shop/billing from main.go
    imports example.com/shop/menu from billing.go
    imports example.com/shop/billing from menu.go: import cycle not allowed
  • An import cycle is a loop of imports: A imports B and B imports A (or a longer loop, A → B → C → A). Go forbids them completely. Packages must form a one-way dependency graph (a picture of which package needs which, with no loops), so each package can be compiled and initialised after the ones it needs. The spec puts it this way: "The importing of packages, by construction, guarantees that there can be no cyclic initialization dependencies."

Three ways out:

Fix How
Move the code ComboPrice is billing logic: move it into billing. Now only billing imports menu.
A new, lower package put what both need (types, constants) into a third package that both import, and that imports neither
An interface at the consumer billing defines a small interface (episode 22) and accepts any value that has the method, so it never imports menu

The interface fix, run for real (billing imports nothing from the shop; menu imports billing):

billing/billing.go:

package billing

// Pricer is anything that can price an item.
type Pricer interface {
    Price(item string) int
}

func Total(p Pricer, items []string) int {
    t := 0
    for _, it := range items {
        t += p.Price(it)
    }
    return t
}

menu/menu.go:

package menu

import "example.com/shop/billing"

type Menu struct{ prices map[string]int }

func New() Menu { return Menu{map[string]int{"chai": 10, "samosa": 15}} }

func (m Menu) Price(item string) int { return m.prices[item] }

func (m Menu) ComboPrice() int { return billing.Total(m, []string{"chai", "samosa"}) - 5 }

main.go:

package main

import (
    "fmt"

    "example.com/shop/billing"
    "example.com/shop/menu"
)

func main() {
    m := menu.New()
    fmt.Println(billing.Total(m, []string{"chai", "chai"}), m.ComboPrice())
}
$ go run .
20 20

Mini project: lay out the shop

The organised shop, as one module with no cycles: main → billing → menu → recipe.

shop/
├── go.mod                          module example.com/shop
├── main.go                         package main: wires it together
├── billing/
│   └── billing.go                  package billing: Total, ComboPrice
└── menu/
    ├── menu.go                     package menu: Items, Price, Recipe
    └── internal/
        └── recipe/
            └── recipe.go           package recipe: only menu can import it

go.mod:

module example.com/shop

go 1.24.7

menu/internal/recipe/recipe.go:

package recipe

// Masala is the secret chai masala mix.
const Masala = "ginger, cardamom, clove"

menu/menu.go:

package menu

import "example.com/shop/menu/internal/recipe"

var Items = []string{"chai", "samosa"}

func Price(item string) int {
    return prices[item]
}

func Recipe() string { return "secret: " + recipe.Masala[:6] + "..." }

var prices = map[string]int{"chai": 10, "samosa": 15}

billing/billing.go:

package billing

import "example.com/shop/menu"

func Total(items []string) int {
    t := 0
    for _, it := range items {
        t += menu.Price(it)
    }
    return t
}

// ComboPrice is chai + samosa with 5 off.
func ComboPrice() int { return Total(menu.Items) - 5 }

main.go:

package main

import (
    "fmt"

    "example.com/shop/billing"
    "example.com/shop/menu"
)

func main() {
    fmt.Println(menu.Recipe())
    fmt.Println("bill:", billing.Total([]string{"chai", "chai", "samosa"}))
    fmt.Println("combo:", billing.ComboPrice())
}
$ go run .
secret: ginger...
bill: 35
combo: 20

go list -deps . prints every package the program needs, dependencies first (the shop's own packages, filtered from the standard library ones):

$ go list -deps . | grep example
example.com/shop/menu/internal/recipe
example.com/shop/menu
example.com/shop/billing
example.com/shop

go vet ./... (the checker from episode 2; ./... means "this folder and every folder below it") reports nothing.

Expert corner

The package name is not the import path

The import path says where the package is; the package clause says what it is called. They usually match the last path element, but don't have to. In a real run, the folder menuv1/ held package menu:

package menu

func Today() string { return "chai and samosa" }
package main

import (
    "fmt"

    "example.com/shop/menuv1"
)

func main() {
    fmt.Println(menu.Today())
}
chai and samosa

The file imports "example.com/shop/menuv1" but writes menu.Today(). Readers can't see that from the import line, which is why the convention is to keep them equal (the exception you will meet in episode 28: major-version folders like /v2, where the package keeps its normal name).

Two different "unexported" errors

Using another package's unexported name gives one of two real messages:

  • name tea not exported by package menu when the package actually uses that name (it was kept in the package's compiled export data);
  • undefined: menu.tea when the name is declared but never used inside its package, so the compiler dropped it.

Both mean the same thing: lowercase names are invisible outside their package. A name starting with _ is never exported either (undefined: menu._Secret).

Program initialisation, step by step

From the spec: "Given the list of all packages, sorted by import path, in each step the first uninitialized package in the list for which all imported packages (if any) are already initialized is initialized." main is always last, because it imports (directly or not) everything else. Inside one package, variable dependency analysis looks only at references to variables, functions and methods of the same package; a dependency hidden behind an interface method call is not detected, and then the order is unspecified. Don't write package-level variables that depend on each other in clever ways.

Who may import what

Rule Enforced by Real message
unused import compiler "strings" imported and not used
lowercase name from another package compiler name discount not exported by package menu
.../internal/... from outside its parent go tool use of internal package ... not allowed
import loop go tool import cycle not allowed
two package clauses in one folder go tool found packages food (extra.go) and menu (menu.go)

go list -f '{{.ImportPath}}: {{.Imports}}' ./... shows each package's direct imports, which is handy when hunting a cycle:

example.com/shop: [example.com/shop/milk example.com/shop/stock fmt]
example.com/shop/milk: [fmt]
example.com/shop/stock: [example.com/shop/milk fmt]

Package-level state is shared by everyone

A package-level variable exists once per program. If two parts of a program change menu.Items, they change the same slice, and if two goroutines (episode 43 onwards) do it at the same time, that is a data race. Exported package-level variables are effectively global variables: prefer unexported ones behind functions, or pass values explicitly.

Common mistakes (and the real messages)

Mistake Real message Why Fix
two functions called price in one package price redeclared in this block one namespace per package separate packages, or different names
fmt.Println(menu.discount) from main name discount not exported by package menu lowercase = unexported export it (Discount) or add an exported function
b.buf on a strings.Builder b.buf undefined (cannot refer to unexported field buf) fields follow the same rule use the exported methods
using menu.Price without importing it undefined: menu no import, no name import "example.com/shop/menu"
crypto/rand and math/rand together rand redeclared in this block both package names are rand crand "crypto/rand"
an import you don't use "strings" imported and not used unused imports are errors remove it, or _ "path" if you need its side effect
decoding a PNG without image/png image: unknown format the decoder registers itself in init _ "image/png"
calling init() yourself undefined: init init can't be referred to put the code in a normal function
two package names in one folder found packages food (extra.go) and menu (menu.go) one folder = one package same package clause in every file
importing menu/internal/recipe from main use of internal package ... not allowed internal = parent folder only expose what's needed from menu
menu imports billing imports menu import cycle not allowed imports must go one way move code, new package, or an interface

Practice

  1. (Homework) Build the shop module from the mini project for real: go mod init example.com/shop, the folders menu, menu/internal/recipe and billing, and run it.
  2. (Homework) From main, print an unexported name of menu, and read the error. Then fix it two ways: by exporting the name, and by adding an exported function.
  3. (Homework) Add two init functions to main.go and one to menu. Predict the order, then run it.
  4. (Homework) Create the menu ⇄ billing cycle, read the error, then break it by moving ComboPrice into billing.
  5. Predict the output:
package main

import "fmt"

var x = y * 2
var y = f()

func f() int {
    fmt.Println("f runs")
    return 21
}

func init() { fmt.Println("init:", x) }

func main() { fmt.Println("main:", x, y) }
  1. Which of these names in package menu can main use? Price, price, _Price, Été, ITEMS.
  2. A package delivery has func DeliveryCharge(km int) int and a variable var deliveryZones = 3. Rename them following the Go blog's advice, and say which should stay unexported.
  3. billing imports menu. Can billing import example.com/shop/menu/internal/recipe? Can menu/specials (a sub-folder of menu) import it?
Solution
  1. The files and the real output (secret: ginger..., bill: 35, combo: 20) are in the mini project section.

  2. With menu.discount you get name discount not exported by package menu. Fix A: rename it Discount everywhere in menu and use menu.Discount. Fix B (often better, because the value stays protected): keep discount and add

// Discount returns today's discount in rupees.
func Discount() int { return discount }

then call menu.Discount() from main.

  1. Imported packages first, so menu's init runs before both of main's. main's two init functions run in the order they appear in the file (or, across files, the order the files are given to the compiler: by name for go run .). Then main.

  2. The error is import cycle not allowed with the chain billing → menu → billing. After moving ComboPrice into billing (as in the mini project), menu no longer imports billing, and the program prints combo: 20.

  3. Real output:

f runs
init: 42
main: 42 21

x needs y, so y = f() runs first (printing f runs), then x = 42. Then init, then main.

  1. Price, Été and ITEMS (they start with an upper case letter). price and _Price are unexported (undefined: menu._Price from outside).

  2. delivery.DeliveryCharge stutters; call it Charge, so callers write delivery.Charge(5). deliveryZones can simply be zones, and should stay unexported unless other packages really need it (then prefer a function such as Zones()).

  3. billing cannot: it is not inside menu/, so the go tool reports use of internal package example.com/shop/menu/internal/recipe not allowed. menu/specials can, because it is below menu/, the folder that contains internal/.

Quick quiz

1. What does this print? (From the video.)

package main

import "fmt"

var a = b + 1
var b = 2

func init() {
    fmt.Print("init ", a, " ")
}

func main() {
    fmt.Println("main", b)
}

A. init 1 main 2 · B. init 3 main 2 · C. compile error · D. main 2 init 3

Answer

B. Package-level variables are initialised by dependency: b = 2 first, then a = 3. init runs before main. Real output: init 3 main 2.

2. The folder example.com/shop/menuv1 contains files that start with package menu. After import "example.com/shop/menuv1", how do you call its Today function?

Answer

menu.Today(). The package name comes from the package clause, not from the folder. (Real run: chai and samosa.)

3. Which import loads a package only for its side effects?

A. import . "image/png" · B. import _ "image/png" · C. import png "image/png" · D. import "image/png"

Answer

B. The blank identifier as the name runs the package's initialisation without giving you a name to use. A is a dot import, C an alias, D a normal import (an error if you never use png).

4. Both stock and main import milk, which has an init function that prints milk: init. How many times is it printed?

Answer

Once. "If multiple packages import a package, the imported package will be initialized only once." (Real run above: one milk: init.)

5. True or false: you can call init() from main to reset a package.

Answer

False. init functions can't be referred to anywhere: undefined: init. Write a normal function such as reset() and call it from init and from wherever you need it.

Interview questions

  1. How does Go decide whether a name is visible outside its package? By its first character: an upper case letter means exported, anything else means unexported. It applies to package-level names, struct fields and methods. There are no access keywords.
  2. What is the difference between an import path and a package name? The import path locates the package (module path + folder, e.g. example.com/shop/menu); the package name, from the package clause, is the identifier you use in code (menu). Convention keeps the name equal to the last path element.
  3. When would you use a blank import? A dot import? Blank: to run a package's init for its side effects, such as registering an image format or a database driver, usually in package main. Dot: almost never; the Code Review Comments allow it only for a special external-test case.
  4. What is the initialisation order of a Go program? Imported packages first (each once, in dependency order), then within a package the package-level variables in dependency order, then init functions in source order (files in the order given to the compiler), and finally main.main.
  5. Why does Go forbid import cycles, and how do you break one? Cycles would make build and initialisation order impossible to define and slow builds down; Go requires a one-way dependency graph. Break them by moving code to the package it belongs to, extracting shared parts into a lower package, or depending on a small interface defined by the consumer.
  6. What does an internal directory do? Packages under .../internal/... can only be imported by code rooted at the parent of internal. It is enforced by the go tool and is the standard way to keep code private to a module or a subtree.
  7. Why are init functions often discouraged in libraries? They run implicitly in every program and test that imports the package, can't return errors, make order-dependent behaviour across files possible, and hide expensive work. Explicit constructor or setup functions are easier to test.
  8. What makes a good package name? Short, lower case, one word, no underscores or mixedCaps, describes what it provides, doesn't stutter with its exported names, and isn't a grab bag like util, common or misc.

Glossary

Term Meaning Example
Package a folder of .go files compiled together, sharing one namespace menu/ with package menu
Package clause the first line of every Go file, naming its package package menu
package main the package that becomes a runnable program; needs func main() main.go
Library package any package that isn't main; code for other packages to use menu, strings
Namespace a space in which every name must be unique one package = one namespace
Redeclared the same name declared twice in one scope price redeclared in this block
Function overloading several functions with one name but different parameters; Go doesn't have it Java's price(String) and price(int)
Module a project: a folder tree with go.mod at the top (episode 2) module example.com/shop
Module path the module's name from go.mod, the prefix of its import paths example.com/shop
go.mod the file that declares the module path and Go version go 1.24.7
Import path the string that locates a package: module path + folder "example.com/shop/menu"
Import declaration the import line that makes another package usable in this file import "fmt"
Package name the name from the package clause, used in code menu in menu.Price
Qualified identifier a package name, a dot, and an exported name menu.Price
Exported identifier a name starting with an upper case letter; usable from other packages Price, Items
Unexported identifier a name starting with a lower case letter or _; only inside its package discount, prices
Encapsulation hiding details behind a small public surface Price uses hidden discount
Package-level variable a variable declared outside any function; lives for the whole program var Items = []string{...}
Package block the top level of a package, outside all functions where var prices is declared
Package naming conventions short, lower case, no _ or mixedCaps, no stutter, no util strconv, not str_conv
Stutter repeating the package name in an exported name menu.MenuPrice
Import alias a local name for an imported package, written before its path crand "crypto/rand"
math/rand fast pseudo-random numbers (games, simulations) rand.Intn(6)
crypto/rand secure random bytes that can't be guessed (passwords, OTPs) crand.Read(otp)
OTP one-time password, e.g. the code sent to your phone 6-digit login code
Blank import importing with _ as the name: load it only for its side effects _ "image/png"
Side effect something a package does just by being loaded registering the PNG decoder
Base64 a way to write any bytes as text using letters, digits, +, / iVBORw0KGgo...
Dot import importing with .: the package's exported names enter the file without a prefix import . "fmt"
imported and not used the compile error for an unused import "strings" imported and not used
Initialisation giving variables their first values and running set-up before main var tax = load(...)
Dependency order a variable is initialised after every variable it uses subtotal, tax, then total
init function func init(), no parameters or results; runs automatically, can't be called func init() { ... }
Package initialisation order imports first (once each), then variables by dependency, then init functions in source order, then main milk, stock, main
go run . build and run the package in the current folder runs the shop
./... "this folder and every folder below it" in go commands go vet ./...
go list -deps lists every package a package needs, dependencies first go list -deps .
internal package a package under an internal/ folder; importable only from its parent folder's tree menu/internal/recipe
Import cycle a loop of imports (A → B → A); Go forbids it import cycle not allowed
Dependency graph a picture of which package imports which; must have no loops main → billing → menu → recipe
Interface at the consumer the using package defines the small interface it needs (episode 22) billing.Pricer
Compile error an error found while building, before the program runs b.buf undefined
Global variable a variable the whole program can reach; exported package-level variables are effectively global menu.Items

Summary

  • A package is one folder of files sharing one namespace; its files start with the same package clause. package main makes a program; everything else is a library.
  • The import path is the module path from go.mod plus the folder (example.com/shop/menu); the package name comes from the package clause and is used as menu.Price.
  • A capital first letter exports a name; lowercase names stay inside their package (name discount not exported by package menu). The rule covers fields and methods too.
  • Name packages short and lower case, without stutter or util/common/misc; keep folder and package names equal.
  • Aliases fix clashes (crand "crypto/rand"); blank imports load a package for its side effects (_ "image/png"); avoid dot imports.
  • Before main: imported packages (each once), then package-level variables in dependency order, then init functions in source order. Don't rely on init order across files, and keep init small.
  • internal/ folders hide packages from everyone outside their parent folder; import cycles are never allowed: move code, extract a lower package, or use an interface.

Next episode: Modules and dependency management: go.mod in depth, go get, go mod tidy, semantic versions, go.sum and the module proxy.