SyntaxStudy
Sign Up
Go Working with Go Modules and Dependencies
Go Beginner 1 min read

Working with Go Modules and Dependencies

Go modules are collections of packages released, versioned, and distributed together. The go.mod file at the root of a module declares the module path, the Go version, and the direct dependencies with their minimum required versions. The go.sum file records the expected cryptographic hashes of specific versions of dependencies to prevent tampering. Adding a dependency is done by importing it in your code and running `go mod tidy`, which resolves the import, downloads the dependency, and updates go.mod and go.sum. You can also add a specific version with `go get module@version`. Dependencies are downloaded to the module cache (GOPATH/pkg/mod) and reused across projects. Semantic versioning (semver) is central to the Go module system. Modules with a major version of v2 or higher must include the major version in their module path (e.g., `github.com/user/pkg/v2`). This rule allows programs to use multiple major versions of the same module simultaneously without conflict, which solves the "diamond dependency" problem.
Example
// go.mod example for a real project
// module github.com/example/webapp
//
// go 1.22
//
// require (
//     github.com/gin-gonic/gin v1.10.0
//     github.com/jmoiron/sqlx v1.4.0
//     github.com/lib/pq v1.10.9
// )

// Common go mod commands:
// $ go mod init github.com/example/webapp    — create a new module
// $ go mod tidy                              — add missing, remove unused deps
// $ go get github.com/gin-gonic/gin@latest   — add/upgrade a dependency
// $ go get github.com/gin-gonic/gin@v1.9.0  — pin to a specific version
// $ go mod vendor                            — copy deps to ./vendor
// $ go mod verify                            — check dep checksums
// $ go list -m all                           — list all module dependencies

// Using an external package (after go mod tidy):
package main

import (
    "fmt"
    "sort"

    "golang.org/x/exp/slices" // example external package
)

func main() {
    // Using the standard library sort package
    words := []string{"banana", "apple", "cherry", "date"}
    sort.Strings(words)
    fmt.Println("sorted:", words)

    // golang.org/x/exp/slices provides generics-based helpers
    nums := []int{5, 2, 8, 1, 9, 3}
    slices.Sort(nums)
    fmt.Println("sorted nums:", nums)

    idx, found := slices.BinarySearch(nums, 8)
    fmt.Printf("found 8 at index %d: %v\n", idx, found)
}