Course › Week 2 · Methods, interfaces, errors, tests › Day 4 · lesson 11 of 42 · 10 min reading + 45–60 min practice
Packages and project layout
Split a program into packages, export with a capital letter, and keep internal code internal.
On this page
Until now every program was one file. Real Go code is split into packages: one folder is one package, and every .go file in that folder belongs to it. A package is Go’s namespace, and there is no other: no classes inside packages, no namespace line that can disagree with the folder.
Today: several files in one package, a package of your own, the one rule for what is visible outside a package, and where the module name comes in.
Files and packages
1. Two files, one package
go mod init bookings, then two files in the same folder, both starting with package main. They share everything, as if they were one file.
package main
import "fmt"
// formatEuros formats an amount in cents as euros: 38850 is "388.50 EUR".
func formatEuros(cents int) string {
return fmt.Sprintf("%d.%02d EUR", cents/100, cents%100)
}
%02d pads a number with zeros to two digits, so 5 cents prints as 05.
package main
import "fmt"
func main() {
fmt.Println(formatEuros(38850))
fmt.Println(formatEuros(4500))
}
388.50 EUR
45.00 EURmain.go calls formatEuros with no import: same package, same folder. go run . compiles every file of the package. There is no require and no autoloader; the folder is the unit.
2. A package in a folder
A folder inside the module is another package. Its files start with the package’s name, which by convention is the folder’s name: pricing/pricing.go starts with package pricing.
// Package pricing computes what a stay costs.
package pricing
// cleaningFeeCents is added once to every stay.
const cleaningFeeCents = 4500
// TotalCents is the price of a stay: the nights, plus the cleaning fee.
func TotalCents(nights, nightlyCents int) int {
return nights*nightlyCents + cleaningFeeCents
}
main imports it by its path: the module name from go.mod, then the folder. Then every use names the package: pricing.TotalCents.
package main import "fmt"import ( "bookings/pricing" "fmt") func main() { fmt.Println(formatEuros(38850)) fmt.Println(formatEuros(4500)) fmt.Println(pricing.TotalCents(3, 12950))}
43350Standard library imports ("fmt") have no dot in their first part; your own start with your module name. gofmt keeps imports sorted, which here puts bookings/pricing before fmt.
The comment before package pricing is the package’s documentation, and the comments above each name are theirs. go doc bookings/pricing prints them, and pkg.go.dev shows them for published packages.
Exported and unexported
3. A capital letter exports a name
A name that starts with a capital letter is exported: visible to other packages. Anything else is visible only inside its own package. TotalCents is exported, cleaningFeeCents is not:
package main
import (
"bookings/pricing"
"fmt"
)
func main() {
fmt.Println(pricing.TotalCents(3, 12950))
fmt.Println(pricing.cleaningFeeCents)
}
# bookings
./main.go:10:22: undefined: pricing.cleaningFeeCentsThat is the whole visibility system: no public, private or protected, just the first letter. It applies to everything: functions, types, constants, variables, struct fields and methods. It is why fmt.Println is capitalised and why the struct fields in Week 1 were.
4. Unexported fields and a constructor
An exported type can have unexported fields. Then code outside the package cannot set them, and the only way to get a valid value is the function the package offers. NewQuote is that function, by convention named New + the type.
// Package pricing computes what a stay costs.package pricing import "errors" // cleaningFeeCents is added once to every stay.const cleaningFeeCents = 4500 // TotalCents is the price of a stay: the nights, plus the cleaning fee.func TotalCents(nights, nightlyCents int) int { return nights*nightlyCents + cleaningFeeCents} // Quote is a price offered to a guest. Its fields are unexported, so only NewQuote can make one,// and every Quote has passed its checks.type Quote struct { nights int nightlyCents int} // NewQuote checks the stay and returns its quote.func NewQuote(nights, nightlyCents int) (Quote, error) { if nights < 1 { return Quote{}, errors.New("a stay needs at least one night") } if nightlyCents < 0 { return Quote{}, errors.New("a price cannot be negative") } return Quote{nights: nights, nightlyCents: nightlyCents}, nil} // TotalCents is the quote's price, with the cleaning fee.func (q Quote) TotalCents() int { return TotalCents(q.nights, q.nightlyCents)}
From outside, the fields do not exist:
package main
import (
"bookings/pricing"
"fmt"
)
func main() {
quote := pricing.Quote{nights: 0, nightlyCents: 12950}
fmt.Println(quote.TotalCents())
}
# bookings
./main.go:9:25: cannot refer to unexported field nights in struct literal of type pricing.Quote
./main.go:9:36: cannot refer to unexported field nightlyCents in struct literal of type pricing.QuoteA Quote with zero nights can no longer be made outside pricing. pricing.Quote{} still compiles, an empty quote, and its zero value should be harmless: here it costs only the cleaning fee. Where even that is wrong, return a pointer from NewQuote and document that callers must use it.
It is PHP’s private properties with a constructor that validates, without the class keyword.
Modules and layout
5. The module path
A module you publish is named after where it lives, so that go get can download it:
go mod init github.com/you/bookings
Then imports read "github.com/you/bookings/pricing". The path is only a name until it is published; nothing is downloaded for your own packages. Use the full path for anything that will be a repository, as every tool in this course will be from logstat v2 on.
6. A typical layout, and internal/
logstat/
├── go.mod (module github.com/you/logstat)
├── main.go (package main: flags, output, exit codes)
└── internal/
└── logparse/
├── logparse.go (package logparse: reading entries)
└── logparse_test.go
A package inside a folder named internal can be imported only by code in the folder that contains internal, here only by logstat itself. Another module that imports github.com/you/logstat/internal/logparse gets a compile error. Use internal/ for every package that is not meant for other people: you can then change it freely.
Keep the layout flat. A small tool is main.go plus one or two packages; there is no src/, and no folder per class. Two packages cannot import each other: an import cycle is a compile error, which keeps the dependencies a tree.
Coming from PHP
| PHP / Laravel | Go |
|---|---|
namespace App\Pricing; + PSR-4 autoloading | the folder pricing/ and package pricing |
use App\Pricing\Calculator; | import "github.com/you/bookings/pricing", then pricing.Name |
public / private / protected | a capital or a lowercase first letter; nothing in between |
| A class per file | any number of types and functions per file; the package is the unit |
@internal in a docblock | internal/, enforced by the compiler |
composer.json name | go.mod module |
The honest difference: there is no protected, because there is no inheritance. Code that would extend a base class in Laravel uses a small interface (the interfaces lesson) or a struct inside another struct in Go.
PracticeHow to Write Go Code, and a package of your own
Read How to Write Go Code, the Go team’s short official guide to modules, packages and go install. Skip its “Testing” section for now; tests come next.
Exercise: move the levels into a package
In a module levels, create internal/level/level.go with package level, the Level type, its constants and its String method from the interfaces lesson, plus a Parse(name string) (Level, error) function. In main.go, parse "WARNING" and "LOUD" and print the results. Decide which names must be exported and which must not.
Show the solution
// Package level is the severity of a log entry.
package level
import "fmt"
// Level is a log entry's severity, from Debug to Error.
type Level int
// The levels, in order of severity.
const (
Debug Level = iota
Info
Warning
Error
)
var names = []string{"DEBUG", "INFO", "WARNING", "ERROR"}
func (l Level) String() string {
if l < 0 || int(l) >= len(names) {
return fmt.Sprintf("Level(%d)", int(l))
}
return names[l]
}
// Parse returns the level with the given name, as Laravel writes it.
func Parse(name string) (Level, error) {
for i, known := range names {
if name == known {
return Level(i), nil
}
}
return Debug, fmt.Errorf("unknown level %q", name)
}
parsed: WARNING 2
error: unknown level "LOUD"The type, its constants and Parse are exported because main uses them. names is not: callers get names through String, and nobody outside can change the slice. Inside the package the type is Level; outside it reads level.Level, so the package name and the type name should not repeat each other more than that.
Remember
- One folder is one package; a capital first letter exports a name, and that is the only visibility rule.
- Unexported fields plus a
New…function keep a type valid. - Name the module after its repository, and put everything not meant for others under
internal/.
Tomorrow: tests, which in Go are ordinary functions in files that end in _test.go.