Crash Courses · PhD
Packages & Modules
Organise code into packages and manage external dependencies
30 min read+185 XP on completionCert: Go Crash Course
Tap any word in the text below to start reading from there.
Packages & Modules
Package Basics
Every .go file belongs to exactly one package. Files in the same directory share a package name:
myapp/
main.go // package main
mathutil/
math.go // package mathutil
math_test.go // package mathutilExported vs Unexported
// mathutil/math.go
package mathutil
// Exported — visible outside the package
func Add(a, b int) int { return a + b }
// unexported — only visible within mathutil
func clamp(n, min, max int) int { ... }go.mod in Practice
go mod init github.com/myorg/myappgo.mod:
module github.com/myorg/myapp
go 1.22
require (
github.com/labstack/echo/v4 v4.12.0
)Adding Dependencies
go get github.com/labstack/echo/v4@latestThis updates go.mod and go.sum. Commit both files.
Tidy
After adding/removing imports, keep your module clean:
go mod tidyThis removes unused dependencies and adds any missing ones.
init()
package config
import "os"
var DatabaseURL string
func init() {
DatabaseURL = os.Getenv("DATABASE_URL")
if DatabaseURL == "" {
DatabaseURL = "postgres://localhost/dev"
}
}Using Your Package
// main.go
package main
import (
"fmt"
"github.com/myorg/myapp/mathutil"
)
func main() {
fmt.Println(mathutil.Add(3, 4)) // 7
}Blank Import
import _ "github.com/lib/pq" // import for side effects (init) onlyUsed for database drivers that register themselves in init().
Vendor Directory
go mod vendorCopies all dependencies into a local vendor/ directory — useful for offline builds or reproducible CI.
Reading progress
0% read
In this module
package
exported name
go.mod
go.sum
0%