managing tools has always been challenging in Go. The Go 1.24 release makes it much simpler. Let's see why.

How to Use the New tool Directive in Go 1.24


The release of Go 1.24 introduces the tool directive for Go modules. This simplifies the process of managing tools, such as linters or generators that are widely used in many Go projects but are not directly used in the codebase. In this blog post, we will explore what the tool directive is, why it matters, and how to use it effectively.

What Is the tool Directive?

The tool directive allows Gophers to specify dependencies for tools used in your Go project without adding those tools as regular dependencies. This is particularly useful for tools like golangci-lint, mockgen, or other command-line utilities that support your development workflow but don’t appear in your import graph.

Previously, developers had to manage such tools using workarounds, such as adding them to a tools.go or a gen.go file or manually installing them outside of Go modules. The tool directive removes this friction by providing a dedicated way to declare these dependencies.


Why Use the tool Directive?

Using the new tool directive offers several benefits:

  1. Separation of Concerns: Tools are clearly distinguished from code dependencies, reducing confusion.
  2. Version Management: You can lock specific versions of tools, ensuring consistent behavior across environments.
  3. Simplified Workflow: Go can record tool dependencies in go.mod, run them with go tool, and install declared tools explicitly when you need binaries in GOBIN.

How to Add Tools to Your Module

Here’s how you can add a tool dependency using the tool directive:

Step 1: Update Your go.mod File

Simply run

go get -tool github.com/golang/mock/mockgen

In this example github.com/golang/mock/mockgen is the path to the tool.

This will add a tool directive to your go.mod file. It will look something like this:

module example.com/myproject

go 1.24

tool github.com/golang/mock/mockgen

Step 2: Run or Install the Tools

After declaring a tool, run it through Go itself:

go tool mockgen -source=internal/service.go -destination=internal/mocks/service_mock.go -package=mocks

If you want to install all declared tools into GOBIN, use:

go install tool

go mod tidy is still useful because it keeps go.mod and go.sum consistent, but it is not the command that installs or runs tools.

Step 3: List the Tools

You can see which tools are declared by running:

go tool

Best Practices for Using the tool Directive

  1. Pin Tool Versions: Always specify a version for your tools to ensure consistency. Go will do this for you.
  2. Document Tool Usage: Include instructions in your project’s README or CONTRIBUTING file on how to install and use the tools.

Reminder..

The tool directive is only available in Go 1.24 and later. Ensure that your contributors use this version or greater.