Modules → Packages
Organizing code across files
Introduction
In this lesson, you'll learn about modules → packages in Go. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, you're familiar with organizing code across files.
Go has its own approach to organizing code across files, which we'll explore step by step.
The Go Way
Let's see how Go handles this concept. Here's a typical example:
// mathutil/mathutil.go
package mathutil
const PI = 3.14159
// Exported (capital letter)
func Add(a, b int) int { return a + b }
// Unexported (lowercase) — like Python's _helper
func helper() {}
// main.go
package main
import (
"fmt"
"github.com/user/app/mathutil"
)
func main() {
fmt.Println(mathutil.Add(2, 3))
fmt.Println(mathutil.PI)
}
// go.mod + go get for dependenciesComparing to Python
Here's how you might have written similar code in Python:
# mathutil.py
PI = 3.14159
def add(a: int, b: int) -> int:
return a + b
def _helper(): # private by convention
pass
# main.py
from mathutil import add, PI
import mathutil
result = add(2, 3)
print(mathutil.PI)
# requirements.txt / pyproject.toml for deps
# pip install requestsYou may be used to different syntax or behavior.
Go exports by capitalization; Python uses _ prefix convention
You may be used to different syntax or behavior.
Go imports by package path; Python imports by module name
You may be used to different syntax or behavior.
go.mod replaces requirements.txt/pyproject.toml
You may be used to different syntax or behavior.
go get replaces pip install
Step-by-Step Breakdown
1. Export Control
Go uses capitalization: capital = exported (public), lowercase = unexported (package-private). Python uses _ by convention.
def add(): ... # public
def _helper(): ... # private by conventionfunc Add() {} // exported
func helper() {} // unexported2. Package Paths
Go imports use full module paths from go.mod. Python imports use relative or absolute module names.
from mathutil import addimport "github.com/user/app/mathutil"
mathutil.Add(2, 3)3. go.mod vs requirements.txt
go.mod defines the module path and dependencies with exact versions. 'go get' installs packages like pip install.
Common Mistakes
When coming from Python, developers often make these mistakes:
- Go exports by capitalization; Python uses _ prefix convention
- Go imports by package path; Python imports by module name
- go.mod replaces requirements.txt/pyproject.toml
Key Takeaways
- Capital = exported; lowercase = unexported
- Package paths vs module names for imports
- go.mod = requirements.txt + setup.py
- go get = pip install