Lesson 15 of 20 · Part 5: Packages and concurrency
Packages and modules
Go packages and modules for beginners. Split code into packages, export names, use internal packages, add third-party modules with go get, and the essential go commands.
5 min read · Updated · Beginner friendly
What you'll learn
- Understand packages, modules, go.mod and import paths
- Split a program into your own packages
- Control visibility with exported names and internal/
- Add, update and tidy third-party dependencies
Every program so far has fit in a single main.go. Real projects grow to dozens or hundreds of files. Go organises code with two simple ideas: packages group related code, and modules group packages into a project you can version and share.
Packages and modules in one picture
- A package is a folder of
.gofiles that all start with the samepackageline. Everything in a package can see everything else in it. - A module is a tree of packages with a
go.modfile at the top. Thego.modfile gives the module its path (its name) and lists its dependencies. - An import path is the module path plus the folder:
example.com/greeter/greet.
You created a module back in lesson 2 with go mod init. Now let’s give it more than one package.
A project with several packages
Here is a small module called example.com/greeter:
greeter/
├── go.mod
├── main.go package main
├── greet/
│ └── greet.go package greet
└── internal/
└── format/
└── format.go package formatmodule example.com/greeter
go 1.24The greet package lives in its own folder. Its package name matches the folder name:
// Package greet builds friendly greetings.
package greet
import "example.com/greeter/internal/format"
// DefaultName is used when no name is given.
const DefaultName = "Gopher"
// Hello returns a greeting for name.
func Hello(name string) string {
if name == "" {
name = DefaultName
}
return punctuate("Hello, " + format.Title(name))
}
// punctuate is unexported: only code inside package greet can call it.
func punctuate(s string) string {
return s + "!"
}// Package format holds text helpers that are private to this module.
package format
import "strings"
// Title upper-cases the first letter of s.
func Title(s string) string {
if s == "" {
return s
}
return strings.ToUpper(s[:1]) + s[1:]
}And main.go imports greet by its full import path:
package main
import (
"fmt"
"example.com/greeter/greet"
)
func main() {
fmt.Println(greet.Hello("ada"))
fmt.Println(greet.Hello(""))
fmt.Println("default name:", greet.DefaultName)
}go run .Hello, Ada!
Hello, Gopher!
default name: GopherAfter importing, you refer to the package by its name (greet), the last part of the import path. Standard library imports ("fmt", "strings") and your own imports are conventionally separated by a blank line.
Exported and unexported names
You have seen this rule throughout the tutorial; now it really matters:
- Names that start with a capital letter (
Hello,DefaultName) are exported: other packages can use them. - Names that start with a lowercase letter (
punctuate) are unexported: they are private to their package.
The rule applies to everything: functions, types, constants, variables, struct fields and methods. Trying to use an unexported name from another package fails to compile:
// in package main
greet.punctuate("hi")undefined: greet.punctuateThis is how Go hides implementation details. Export only what other packages need; keep everything else lowercase so you can change it freely later.
internal packages
A package inside a folder named internal can only be imported by code in the parent of that internal folder (here, anything inside greeter/). Code in other modules can’t import example.com/greeter/internal/format, even though Title is exported. Use internal/ for helpers that are shared within your project but not part of its public API.
Package naming tips
- Short, lowercase, single words:
greet,format,storage,auth. No underscores or mixedCaps. - Name the package for what it provides, not “utils” or “common”.
- Don’t repeat the package name in exported names: callers write
greet.Hello, notgreet.GreetHello. Likewise the standard library hashttp.Server, nothttp.HTTPServer. - Write a doc comment above the
packageline and above each exported name, starting with that name.go docand pkg.go.dev display them.
Import tricks
import (
"fmt"
_ "image/png" // blank import: run the package's init code only
mrand "math/rand/v2" // alias to avoid a name clash with crypto/rand
str "strings" // alias: refer to the package as str
)You’ll rarely need aliases. Blank imports are used to register plug-ins, such as image formats or database drivers.
init functions
A package can declare func init(). It runs automatically, once, when the program starts, before main. It’s useful for one-off setup, but keep it rare: code that runs implicitly is harder to follow and test.
Using third-party modules
Thousands of open-source Go modules are listed on pkg.go.dev. To use one, import it in your code and let the go command fetch it. For example, to generate unique IDs with github.com/google/uuid:
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
fmt.Println(uuid.NewString())
}go get github.com/google/uuid
go run .3f1c2a8e-6b9d-4c41-9f0a-2d7e5b8c1a34(Your ID will be different every time.)
go get downloads the module and adds it to go.mod:
module example.com/greeter
go 1.24
require github.com/google/uuid v1.6.0It also creates go.sum, which records a checksum of every dependency so that a tampered download is detected. Commit both go.mod and go.sum to version control.
The go command toolbox
| Command | What it does |
|---|---|
go run . |
Compile and run the package in the current folder |
go build ./... |
Compile every package in the module (./... means “this folder and below”) |
go test ./... |
Run all tests (lesson 19) |
go fmt ./... |
Format all code |
go vet ./... |
Report suspicious code that compiles but is probably wrong |
go get pkg@version |
Add or update a dependency, e.g. @latest |
go mod tidy |
Add missing and remove unused dependencies |
go doc greet.Hello |
Show documentation in the terminal |
go install pkg@latest |
Build and install a command-line tool |
Run go mod tidy whenever you add or remove imports; it keeps go.mod and go.sum accurate.
Common mistakes
Folder and package name don’t match. It’s allowed, but confusing. Keep them the same (except main).
Import cycles. If package a imports b, then b can’t import a. The compiler reports import cycle not allowed. Fix it by moving the shared code into a third package that both import.
Forgetting to export. If another package says undefined: greet.hello, rename it to Hello.
Using the module path wrong. Imports use the module path from go.mod plus the folder, not a relative path like ./greet.
Exercises
1. A mathx package. In a new module, create a package mathx with an exported Max(nums ...int) int and an unexported helper. Call mathx.Max from main.
Show solution
calc/
├── go.mod (module example.com/calc)
├── main.go
└── mathx/
└── mathx.go// Package mathx has small math helpers.
package mathx
// Max returns the largest of nums, or 0 if nums is empty.
func Max(nums ...int) int {
if len(nums) == 0 {
return 0
}
best := nums[0]
for _, n := range nums[1:] {
best = larger(best, n)
}
return best
}
func larger(a, b int) int {
if a > b {
return a
}
return b
}package main
import (
"fmt"
"example.com/calc/mathx"
)
func main() {
fmt.Println(mathx.Max(3, 17, 8))
}172. Read the docs. Run go doc strings.Fields and go doc fmt.Stringer in your terminal. Then find the same pages on pkg.go.dev.
Recap
- A package is a folder of files with the same
packagename; a module is a tree of packages with ago.mod. - Import your own packages by module path plus folder:
example.com/greeter/greet. - Capitalised names are exported; lowercase names are private to the package;
internal/limits who can import. go getadds dependencies;go mod tidycleans them up; commitgo.modandgo.sum.
Next: Go’s headline feature, goroutines and channels.
Finished this lesson?
Your progress is saved in this browser only.