SyntaxStudy
Sign Up
Go Setting Up a Go Module
Go Beginner 1 min read

Setting Up a Go Module

Go modules are the official dependency management system introduced in Go 1.11 and made the default in Go 1.16. A module is a collection of related Go packages that are versioned together. Every module starts with a go.mod file that declares the module path (used as the import prefix) and the minimum Go version required. Creating a new module is done with the command `go mod init `. This generates a go.mod file. When you add imports and run `go mod tidy`, Go automatically resolves, downloads, and records the required dependencies in go.mod and a go.sum checksum file. Understanding the module system is essential before building anything non-trivial in Go. It controls how packages are imported, versioned, and shared. The module path is typically a URL-style identifier such as `github.com/user/project`, which allows Go tooling to fetch dependencies directly from source control.
Example
// Step 1: initialise a new module (run in terminal)
// $ go mod init github.com/example/myapp

// go.mod (auto-generated)
// module github.com/example/myapp
// go 1.22

// Step 2: project layout
// myapp/
//   go.mod
//   go.sum
//   main.go
//   internal/
//     greet/
//       greet.go

// internal/greet/greet.go
package greet

import "fmt"

// Hello returns a greeting string.
func Hello(name string) string {
    return fmt.Sprintf("Hello, %s!", name)
}

// main.go
package main

import (
    "fmt"
    "github.com/example/myapp/internal/greet"
)

func main() {
    msg := greet.Hello("world")
    fmt.Println(msg)
}

// Step 3: run
// $ go run .
// Hello, world!