A linter is an automatic tool to analyze code and catch errors.
To understand why linters are important, let’s take one concrete example. In mistake #1, “Unintended variable shadowing,” we discussed potential errors related to variable shadowing. Using vet, a standard linter from the Go toolset, and shadow, we can detect shadowed variables:
package main import "fmt" func main() { i := 0 if true { i := 1 fmt.Println(i) } fmt.Println(i) }
zzh@ZZHPC:/zdata/Github/ztest$ go run main.go 1 0
Because vet is included with the Go binary, let’s first install shadow, link it with Go vet, and then run it on the previous example:
zzh@ZZHPC:/zdata/Github/ztest$ go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latest go: downloading golang.org/x/tools v0.18.0 go: downloading golang.org/x/mod v0.15.0 zzh@ZZHPC:/zdata/Github/ztest$ go vet -vettool $(which shadow) # github.com/ZhangZhihuiAAA/ztest ./main.go:8:9: declaration of "i" shadows declaration at line 6
As we can see, vet informs us that the variable i is shadowed in this example. Using appropriate linters can help make our code more robust and detect potential errors.
NOTE that 'go vet' is a different tool with 'go tool vet':
zzh@ZZHPC:/zdata/Github/ztest$ go tool vet vet is a tool for static analysis of Go programs. Usage of vet: vet unit.cfg # execute analysis specified by config file vet help # general help, including listing analyzers and flags vet help name # help on specific analyzer and its flags
Here is a list that you may want to use daily:
https://golang.org/cmd/vet/—A standard Go analyzer
https://github.com/kisielk/errcheck—An error checker
https://github.com/fzipp/gocyclo—A cyclomatic complexity analyzer
https://github.com/jgautheron/goconst—A repeated string constants analyzer
Besides linters, we should also use code formatters to fix code style. Here is a list of some code formatters for you to try:
https://golang.org/cmd/gofmt/—A standard Go code formatter
https://godoc.org/golang.org/x/tools/cmd/goimports—A standard Go imports formatter
Meanwhile, we should also look at golangci-lint (https://github.com/golangci/golangci-lint). It’s a linting tool that provides a facade on top of many useful linters and formatters. Also, it allows running the linters in parallel to improve analysis speed, which is quite handy.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律