今天给项目加上了golangci检测,结果运行gosimple的时候报了这样一个问题:
xxx.go:289:10: S1034: assigning the result of this type assertion to a variable (switch err := err.(type)) could eliminate the following type assertions:
xxx.go:291:14 (gosimple)
switch err.(type) {
^
这个问题对应的程序是这样的:
switch err.(type) {
case *fatalException:
msg := err.(*fatalException).Message
default:
//...
}
gosimple是用来检测代码是不是有可以简化的地方的,可是看这段代码,感觉没啥简化的空间了啊。。。
于是认真翻译了一下这句话:
将类型断言的结果分配给变量,可以去除后续的断言
乍一看没懂,可是仔细它给的信息,发现它告诉你了,就是这样改:
switch err := err.(type)
纳尼?还有这种写法??靠不靠谱啊。。。
于是我写了段代码,验证下:
package main
import "fmt"
func main() {
var a interface{}
a = "123"
switch a := a.(type) {
case int:
fmt.Printf("int %d", a)
case string:
fmt.Printf("string %s", a)
default:
fmt.Println("unknown")
}
}
运行结果是这样的:
到这我就明白了,把类型判断的结果分配给变量,这个变量就变成了类型转换后的结果,这样在对应case里处理的时候,就不用再来一次类型转换了,比如我最开始给出的那段代码,改成下面这样就可以了:
switch err := err.(type) {
case *fatalException:
msg := err.Message
default:
//...
}
这么一看,确实是简化了,哈哈,还是怪自己才疏学浅了
更多推荐
assigning the result of this type assertion to a variable could eliminate the fo
发布评论