go get -tool怎么用

张开发
2026/4/21 6:11:47 15 分钟阅读

分享文章

go get -tool怎么用
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-lintlatest # 添加特定版本 go get -tool github.com/go-delve/delve/cmd/dlvv1.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 -toolgo tooltools.go//go:build tools污染requirehack 方式go get -toolMakefile中go run临时下载无缓存go get -tool实际示例bash复制# 1. 添加常用开发工具 go get -tool github.com/golangci/golangci-lint/cmd/golangci-lintlatest go get -tool golang.org/x/tools/cmd/goimportslatest go get -tool github.com/air-verse/airlatest # 热重载 # 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 版本才能使用此功能。

更多文章