ZhangZhihui's Blog  

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.

posted on   ZhangZhihuiAAA  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
 
点击右上角即可分享
微信分享提示