assigning the result of this type assertion to a variable could eliminate the followin assertion解决

编程入门 行业动态 更新时间:2024-10-24 16:32:13

今天给项目加上了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

本文发布于:2023-06-13 22:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1412468.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:type   result   assigning   assertion   followin

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!