Golinter提示parsing.tokenType类型Switch缺case,如何用Default规避?
问题:如何避免Go exhaustive linter对带default分支的switch报错?
我编写了如下Go代码:
token := NextToken() switch token.Typ { case tokenEOF: return nil case tokenMentionTargetedControl: // do stuff default: return nil }
其中token.Typ为parsing.tokenType枚举类型,golinter触发了exhaustive规则报错:
missing cases in switch of type parsing.tokenType: parsing.tokenControl, parsing.tokenLinkControl, parsing.tokenMailtoControl, parsing.tokenMentionControl, parsing.tokenChannelControl, parsing.tokenText (exhaustive)
由于已设置default分支处理其余情况,不想为每个枚举值编写case,请问如何避免该报错?
解决方案
有几种简洁的方式可以跳过exhaustive linter的检查:
添加lint忽略注释:在switch语句上方或同一行添加
//nolint:exhaustive注释,明确告知linter跳过当前switch的穷尽性检查:token := NextToken() //nolint:exhaustive switch token.Typ { case tokenEOF: return nil case tokenMentionTargetedControl: // do stuff default: return nil }或者直接写在switch行末尾:
switch token.Typ { //nolint:exhaustive // ... }全局配置忽略(批量场景):如果多个地方都需要忽略该枚举类型的检查,可以在golint的配置文件(比如
.golangci.yml)中添加exhaustive的忽略规则:linters-settings: exhaustive: exclude: - "parsing.tokenType"临时转换类型(不推荐):将枚举类型转换为
interface{}后再做switch,这样exhaustive不会识别为枚举类型检查,但会丢失类型安全性,仅作为临时 workaround 使用:switch interface{}(token.Typ).(type) { case tokenEOF: return nil case tokenMentionTargetedControl: // do stuff default: return nil }
内容的提问来源于stack exchange,提问作者Raul Quinzani
相关产品推荐
相关产品推荐

