intermediate Step 11 of 15

Packages and Modules

Go Programming

Packages and Modules

Go's module system manages dependencies and code organization. Every Go file belongs to a package, and the module system (introduced in Go 1.11) handles versioning and dependency resolution. Understanding how to structure packages, manage dependencies with go.mod, and follow Go conventions for package design is essential for building maintainable Go applications.

Package Organization

# Initialize module
go mod init github.com/user/myproject

# Add a dependency
go get github.com/gin-gonic/gin

# Project structure
myproject/
├── go.mod
├── go.sum
├── main.go
├── internal/           # Private to this module
│   ├── handlers/
│   │   └── user.go
│   └── models/
│       └── user.go
└── pkg/                # Public packages
    └── utils/
        └── helpers.go
// internal/models/user.go
package models

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

// internal/handlers/user.go
package handlers

import "github.com/user/myproject/internal/models"

func GetUsers() []models.User {
    return []models.User{
        {ID: 1, Name: "Alice", Email: "alice@example.com"},
    }
}
Pro tip: Package names should be short, lowercase, and singular (e.g., user not users). Avoid generic names like util or common. Use the internal/ directory for packages that should not be imported by other modules.

Key Takeaways

  • Use go mod init to create a module and go get to add dependencies.
  • Exported names start with uppercase; unexported names start with lowercase.
  • The internal/ directory restricts package visibility to the parent module.
  • Use struct tags (`json:"name"`) for JSON marshaling and other metadata.
  • Run go mod tidy to clean up unused dependencies.