>_
GolangStepByStep
Intern

Packages & Modules

Organise code into packages the Go way — go mod, imports, and visibility

# Why Packages and Modules Matter

Clean package boundaries make large codebases maintainable, while modules provide reproducible dependency management and versioned distribution.

# Visibility and API Surface

Capitalized identifiers are exported. Keep internals unexported to preserve invariants.

type Config struct { // exported
    Host string
    Port int
}

func defaultPort() int { // unexported
    return 8080
}

# Modules and go.mod

A module groups packages under one versioned dependency graph defined by go.mod.

module github.com/mycompany/myproject

go 1.22

require github.com/gin-gonic/gin v1.9.1

# Import Patterns and init

Use aliases to resolve name collisions, blank imports for side effects, and keep init() minimal.

# Practice Challenge

Create a multi-package module with go mod init, an exported utility package, and a `main` package that imports and uses it.

// myproject/
//   go.mod
//   main.go
//   mathutil/math.go

⚡ Key Takeaways

  • Use capitalization rules intentionally for public API design
  • Keep module metadata tidy with go mod tidy
  • Use internal packages to enforce private module boundaries
  • Prefer small, cohesive packages with clear responsibility
practice & review