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
.gofiles that are compiled together and share one namespace. Names in different packages never clash:menu.Priceanddelivery.Pricecan both exist. - The package clause is the first statement of every Go file: the keyword
packageand a name. Every file in one folder must use the same package name. If they don't, the Go tool refuses (real output, withmenu/extra.gosayingpackage food):
main.go:6:5: found packages food (extra.go) and menu (menu.go) in /tmp/g/ns2x/menu
package mainis special: it is the package that becomes a runnable program, and it must havefunc 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.modfile at the top. Themoduleline ingo.modgives 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 foldermenuinside moduleexample.com/shopis 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,discountandpricesare 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 thatPriceusespriceseven thoughpricesis declared below it: order doesn't matter at package level. - By convention the folder name and the package name are the same (
menu/holdspackage menu). - Look at the first letters:
ItemsandPriceare capitalised;discountandpricesare 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.Priceis a package name, a dot, and a name. Without the import,menumeans nothing:./main.go:6:17: undefined: menu(real output, from amain.gothat 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
publicorprivatekeywords: 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
menucan touchdiscount, 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;+ 1makes a dice roll (1 to 6). The program printsdice ok: trueinstead of the number so the output is the same on every run.crand.Read(otp)fills the slice with secure random bytes.strforstringsworks 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.MenuPricesays "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(fromdatabase/sql) in itsinit, so programs import it with_and then open the database by the driver's name. Put blank imports inpackage 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
PrintlnorSprintcomes 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
totalis written first but needssubtotalandtax, so Go initialisessubtotal(100), thentax(100/20 = 5), thentotal(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
milkwas initialised once, beforestockandmain, even though both import it.go run .hands the files to the compiler sorted by name (a.go, thenb.go);go run b.go a.gohands them in the order you typed. The init order ofmain's two files changed with it. So never rely on the order of init functions in different files.- Keep
initsmall. 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 likemenu.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 menuwhen the package actually uses that name (it was kept in the package's compiled export data);undefined: menu.teawhen 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
- (Homework) Build the shop module from the mini project for real:
go mod init example.com/shop, the foldersmenu,menu/internal/recipeandbilling, and run it. - (Homework) From
main, print an unexported name ofmenu, and read the error. Then fix it two ways: by exporting the name, and by adding an exported function. - (Homework) Add two init functions to
main.goand one tomenu. Predict the order, then run it. - (Homework) Create the
menu⇄billingcycle, read the error, then break it by movingComboPriceintobilling. - 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) }
- Which of these names in package
menucanmainuse?Price,price,_Price,Été,ITEMS. - A package
deliveryhasfunc DeliveryCharge(km int) intand a variablevar deliveryZones = 3. Rename them following the Go blog's advice, and say which should stay unexported. billingimportsmenu. Canbillingimportexample.com/shop/menu/internal/recipe? Canmenu/specials(a sub-folder ofmenu) import it?
Solution
-
The files and the real output (
secret: ginger...,bill: 35,combo: 20) are in the mini project section. -
With
menu.discountyou getname discount not exported by package menu. Fix A: rename itDiscounteverywhere inmenuand usemenu.Discount. Fix B (often better, because the value stays protected): keepdiscountand add
// Discount returns today's discount in rupees.
func Discount() int { return discount }
then call menu.Discount() from main.
-
Imported packages first, so
menu's init runs before both ofmain'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 forgo run .). Thenmain. -
The error is
import cycle not allowedwith the chainbilling → menu → billing. After movingComboPriceintobilling(as in the mini project),menuno longer importsbilling, and the program printscombo: 20. -
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.
-
Price,ÉtéandITEMS(they start with an upper case letter).priceand_Priceare unexported (undefined: menu._Pricefrom outside). -
delivery.DeliveryChargestutters; call itCharge, so callers writedelivery.Charge(5).deliveryZonescan simply bezones, and should stay unexported unless other packages really need it (then prefer a function such asZones()). -
billingcannot: it is not insidemenu/, so the go tool reportsuse of internal package example.com/shop/menu/internal/recipe not allowed.menu/specialscan, because it is belowmenu/, the folder that containsinternal/.
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
- 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.
- 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. - When would you use a blank import? A dot import? Blank: to run a package's
initfor its side effects, such as registering an image format or a database driver, usually inpackage main. Dot: almost never; the Code Review Comments allow it only for a special external-test case. - 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
initfunctions in source order (files in the order given to the compiler), and finallymain.main. - 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.
- What does an
internaldirectory do? Packages under.../internal/...can only be imported by code rooted at the parent ofinternal. It is enforced by the go tool and is the standard way to keep code private to a module or a subtree. - Why are
initfunctions 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. - 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,commonormisc.
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 mainmakes a program; everything else is a library. - The import path is the module path from
go.modplus the folder (example.com/shop/menu); the package name comes from the package clause and is used asmenu.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 keepinitsmall. - 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.