Sorting Dependencies in go.mod Alphabetically

Learn why alphabetical sorting of go.mod dependencies matters for readability, merge conflict reduction, and consistent code review. Understand how go mod tidy and formatters sort entries.

Dependencies

Detailed Explanation

Sorting Dependencies Alphabetically

Alphabetical sorting of require entries is the standard convention in the Go ecosystem. Both go mod tidy and the official Go tooling sort entries alphabetically by module path.

Why Sort?

  1. Predictable location: Finding a specific dependency is O(log n) with a binary search mentality
  2. Merge conflict reduction: When two branches add different dependencies, sorted entries are less likely to conflict
  3. Clean diffs: Changes are localized to specific positions rather than randomly scattered
  4. Review efficiency: Reviewers can quickly spot new, removed, or changed dependencies

Sorting Rules

Go sorts module paths lexicographically (byte-by-byte string comparison):

require (
    github.com/aws/aws-sdk-go   v1.49.0
    github.com/gin-gonic/gin    v1.9.1
    github.com/spf13/cobra      v1.8.0
    golang.org/x/text           v0.14.0
    google.golang.org/grpc      v1.60.1
)

Note: github.com entries come before golang.org entries because gi < go in ASCII order.

Version Alignment

After sorting, versions should be aligned into a column for readability:

// Before: misaligned
github.com/aws/aws-sdk-go v1.49.0
github.com/gin-gonic/gin v1.9.1
google.golang.org/grpc v1.60.1

// After: aligned
github.com/aws/aws-sdk-go v1.49.0
github.com/gin-gonic/gin  v1.9.1
google.golang.org/grpc    v1.60.1

Formatter Behavior

A go.mod formatter:

  1. Parses all require entries
  2. Separates direct and indirect dependencies
  3. Sorts each group alphabetically
  4. Aligns version numbers with spaces
  5. Outputs two clean require blocks

Manual Sorting Pitfalls

Manually sorting can introduce errors:

  • Moving an entry between direct/indirect blocks
  • Accidentally duplicating an entry
  • Breaking tab-aligned formatting

Using a formatter eliminates these risks.

Use Case

Consistent sorting is particularly important in large teams and monorepos where multiple developers modify go.mod concurrently. Formatting go.mod before committing reduces merge conflicts, makes code reviews faster, and ensures the file stays clean. CI pipelines can enforce sorted go.mod by running the formatter in check mode.

Try It — go.mod Formatter

Open full tool