JSTAcademy
0 XP
Dashboard
Crash Courses
Packages & Modules
30 min
PhD+185 XP
Crash Courses · PhD

Packages & Modules

Organise code into packages and manage external dependencies
30 min read+185 XP on completionCert: Go Crash Course
Tap any word in the text below to start reading from there.

Packages & Modules

Package Basics

Every .go file belongs to exactly one package. Files in the same directory share a package name:

myapp/
  main.go          // package main
  mathutil/
    math.go        // package mathutil
    math_test.go   // package mathutil

Exported vs Unexported

// mathutil/math.go
package mathutil

// Exported — visible outside the package
func Add(a, b int) int { return a + b }

// unexported — only visible within mathutil
func clamp(n, min, max int) int { ... }

go.mod in Practice

go mod init github.com/myorg/myapp

go.mod:

module github.com/myorg/myapp

go 1.22

require (
    github.com/labstack/echo/v4 v4.12.0
)

Adding Dependencies

go get github.com/labstack/echo/v4@latest

This updates go.mod and go.sum. Commit both files.

Tidy

After adding/removing imports, keep your module clean:

go mod tidy

This removes unused dependencies and adds any missing ones.

init()

package config

import "os"

var DatabaseURL string

func init() {
    DatabaseURL = os.Getenv("DATABASE_URL")
    if DatabaseURL == "" {
        DatabaseURL = "postgres://localhost/dev"
    }
}

Using Your Package

// main.go
package main

import (
    "fmt"
    "github.com/myorg/myapp/mathutil"
)

func main() {
    fmt.Println(mathutil.Add(3, 4)) // 7
}

Blank Import

import _ "github.com/lib/pq" // import for side effects (init) only

Used for database drivers that register themselves in init().

Vendor Directory

go mod vendor

Copies all dependencies into a local vendor/ directory — useful for offline builds or reproducible CI.

0%