Packages & Modules Explained | Go Tutorial #21
Video: Packages & Modules Explained | Go Tutorial #21 by Taught by Celeste AI - AI Coding Coach
Watch full page →Packages & Modules Explained | Go Tutorial #21
Organizing Go code effectively requires understanding packages and modules. This tutorial explains how to initialize Go modules, create custom packages, control visibility with capitalization, and import local packages to build clean, maintainable multi-package projects.
Code
// main.go
package main
import (
"fmt"
"example.com/mymodule/mathutil" // import custom package
)
func main() {
fmt.Println("Sum:", mathutil.Add(3, 5))
fmt.Println("Product:", mathutil.Multiply(3, 5))
}
// mathutil/mathutil.go
package mathutil
// Add returns the sum of two integers.
// Public function because it starts with a capital letter.
func Add(a, b int) int {
return a + b
}
// multiply returns the product of two integers.
// Private function because it starts with a lowercase letter.
func multiply(a, b int) int {
return a * b
}
// Multiply is a public wrapper calling the private multiply function.
func Multiply(a, b int) int {
return multiply(a, b)
}
// To initialize the module, run in your project root:
// go mod init example.com/mymodule
Key Points
- Use
go mod initto create a new module and manage dependencies. - Packages group related Go files; each package has its own directory.
- Capitalized names are exported (public), while lowercase names remain private within the package.
- Import local packages using the module path plus package directory, e.g.,
example.com/mymodule/mathutil. - Organizing code into multiple packages improves readability and reusability in larger projects.