go get -tool是 Go 1.24 版本引入的新功能,用于将工具依赖(tool dependencies)添加到go.mod文件中,而不是下载到go.mod的require部分或单独维护tools.go文件。
基本用法
bash
复制
# 添加一个工具依赖(例如 golangci-lint) go get -tool github.com/golangci/golangci-lint/cmd/golangci-lint@latest # 添加特定版本 go get -tool github.com/go-delve/delve/cmd/dlv@v1.22.0核心作用
表格
| 特性 | 说明 |
|---|---|
| 隔离工具依赖 | 工具不会出现在require中,避免污染主模块依赖 |
go.mod 新增tool指令 | 在go.mod中生成独立的tool区块 |
| 版本锁定 | 像普通依赖一样锁定工具版本 |
| 无需 tools.go | 不再需要//go:build tools的 hack 方式 |
go.mod 中的变化
执行go get -tool后,go.mod会新增:
go
复制
tool ( github.com/golangci/golangci-lint/cmd/golangci-lint v1.57.2 github.com/go-delve/delve/cmd/dlv v1.22.0 ) require ( // 你的普通依赖,工具不会出现在这里 )运行工具
添加后,使用go tool运行:
bash
复制
# 运行已添加的工具 go tool golangci-lint run ./... # 查看所有可用工具 go tool对比旧方案
表格
| 方式 | 缺点 | Go 1.24+ 推荐 |
|---|---|---|
go install全局安装 | 无版本锁定,多项目冲突 | go get -tool+go tool |
tools.go+//go:build tools | 污染require,hack 方式 | go get -tool |
Makefile中go run | 临时下载,无缓存 | go get -tool |
实际示例
bash
复制
# 1. 添加常用开发工具 go get -tool github.com/golangci/golangci-lint/cmd/golangci-lint@latest go get -tool golang.org/x/tools/cmd/goimports@latest go get -tool github.com/air-verse/air@latest # 热重载 # 2. 在 CI/CD 中使用 go tool golangci-lint run ./... # 3. 团队成员只需 go mod tidy # 会自动安装 tool 依赖 go tool <tool-name>注意事项
需要 Go 1.24+:此功能在 Go 1.24 中引入,旧版本不支持
工具必须是 main 包:只能添加可执行的命令(
package main)不影响构建:
tool依赖不会被编译进你的二进制文件
如果你当前 Go 版本低于 1.24,需要先升级 Go 版本才能使用此功能。