关于go:go-常用代码检查工具

2次阅读

共计 599 个字符,预计需要花费 2 分钟才能阅读完成。

如何主动发现 variable shadowing

靠人肉去排查还是容易脱漏的,Go 工具链里有一个 shadow 命令能够帮忙咱们排查代码里潜在的 variable shadowing 问题。

第一步,装置 shadow 命令

go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow

第二步,应用 shadow 查看代码里是否有 variable shadowing

go vet -vettool=$(which shadow)

比方,我查看后的后果如下:

$ go vet -vettool=$(which shadow)
# example.com/shadow
./main.go:9:6: declaration of "i" shadows declaration at line 8

此外,shadow 命令也能够独自应用,不须要联合 go vet。shadow 前面须要带上 package 名称或者.go 源代码文件名。

$ shadow example.com/shadow
11-variable-shadowing/main.go:9:6: declaration of "i" shadows declaration at line 8
$ shadow main.go
11-variable-shadowing/main.go:9:6: declaration of "i" shadows declaration at line 8
正文完
 0