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 2024-02-14 17:16  ZhangZhihuiAAA  阅读(30)  评论(0)    收藏  举报