Packages: Organizing Go Code
Package declarations, imports, and exported names
What Is a Package?
Every Go source file belongs to a package. The package name appears at the top of every file. Packages group related code and control visibility:
// file: math/calc.go
package math
// Exported — accessible from other packages (capital letter)
func Add(a, b int) int { return a + b }
// Unexported — package-private (lowercase)
func helper() int { return 42 }Package Declaration and Import Path
The package name (short) differs from the import path (full module path/directory):
// Import path: github.com/myapp/util/stringutil
// Package name: stringutil (last segment by convention)
package stringutil
func Reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}All lessons in this course
- Packages: Organizing Go Code
- Go Modules with go mod
- Adding External Dependencies
- Internal Packages and Workspaces