首页 > 其他分享 >Go 100 mistakes - #16: Not using linters

Go 100 mistakes - #16: Not using linters

时间:2024-02-14 17:22:05浏览次数:43  
标签:vet 16 linters Go mistakes https go org

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)
}

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.

标签:vet,16,linters,Go,mistakes,https,go,org
From: https://www.cnblogs.com/zhangzhihui/p/18015329

相关文章

  • Go 100 mistakes - #15: Missing code documentation
    Documentationisanimportantaspectofcoding.ItsimplifieshowclientscanconsumeanAPIbutcanalsohelpinmaintainingaproject.InGo,weshouldfollowsome rulestomakeourcodeidiomatic.First,everyexportedelementmustbedocumented.Wheth......
  • Go 100 mistakes - #11: Not using the functional options pattern
      Here,WithPortreturnsaclosure.Aclosureisananonymousfunctionthatreferences variablesfromoutsideitsbody;inthiscase,theportvariable.Theclosurerespectsthe Optiontypeandimplementstheport-validationlogic.Eachconfigfieldr......
  • Codeforces 1657E Star MST
    记边权上限为\(W\)。转化一下即为\((1,i)(i\in[2,n])\)的边组成的也是原图的最小生成树。考虑\(\text{Prim}\)的方法求最小生成树。从\(1\)号点开始扩展,每次都会选取距离当前已扩展到的点最近的点\(u\)。为了保证\((1,u)\)的边在最小生成树中,需要满足对于已经扩......
  • poj 1416 Shredding Company
    1416--ShreddingCompany(poj.org)#include<iostream>#include<cstring>usingnamespacestd;charnum[10];intt,max_cnt,max_sum,shred_cnt,ans[10],tmp_ans[10];//目标,最大值个数,最大值,切割次数,最后答案,临时答案voidDFS(intbegin,intnow_sum,intcnt){//切的位......
  • Go 100 mistakes - #10: Not being aware of the possible problems with type embedd
     Becausethemutexisembedded,wecandirectlyaccesstheLockandUnlockmethods fromtheireceiver.Wementionedthatsuchanexampleisawrongusageoftypeembedding.What’s thereasonforthis?Sincesync.Mutexisanembeddedtype,theLockand......
  • Codeforces Round 169 (Div. 2)C. Little Girl and Maximum Sum(差分、贪心)
    目录题面链接题意题解代码总结题面链接C.LittleGirlandMaximumSum题意给q个[l,r]将所有这些区间里面的数相加和最大。可以进行的操作是任意排列数组题解对出现的每个区间内的位置加上1,代表权值操作完之后求一遍前缀和,得到每个位置的权值然后贪心的考虑,权值越大,应......
  • day16_防火墙服务
    基础服务管理防火墙是什么查找防火墙服务名的技巧[root@yuchao-linux01~]#systemctllist-units|grepfirefirewalld.serviceloadedactiverunningfirewalld-d......
  • Go 100 mistakes - #9: Being confused about when to use generics
    Go1.18addsgenericstothelanguage.Inanutshell,thisallowswritingcodewithtypes thatcanbespecifiedlaterandinstantiatedwhenneeded. Onelastthingtonoteabouttypeparametersisthattheycan’tbeusedwith methodarguments,onlywith......
  • Go 100 mistakes - #8: any says nothing
    WithGo1.18,thepredeclaredtypeanybecameanaliasforanempty interface;hence,alltheinterface{}occurrencescanbereplacedbyany. IffuturedevelopersneedtousetheStore struct,theywillprobablyhavetodigintothedocumentationorre......
  • Go 100 mistakes - #7: Returning interfaces
       Allinall,inmostcases,weshouldn’treturninterfacesbutconcreteimplementa-tions.Otherwise,itcanmakeourdesignmorecomplexduetopackagedependencies andcanrestrictflexibilitybecausealltheclientswouldhavetorelyonthesam......