var client *http.Client var err error if tracing { client, err = createClientWithTracing() } else { ... } if err != nil { // 防止重复代码 return err }
或者内层的变量声明换一个变量名字,这样就不容易出错了。
我们也可以使用工具分析代码是否有 shadow,先安装一下工具:
1
go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow
然后使用 shadow 命令:
1 2 3 4
go vet -vettool=/path/to/shadow ./main.go # command-line-arguments ./main.go:15:3: declaration of "client" shadows declaration at line 13 ./main.go:21:3: declaration of "client" shadows declaration at line 13