简体   繁体   English

golangci-lint 常量显式类型

[英]golangci-lint constant explicit type

I have a question about golangci-lint.我有一个关于 golangci-lint 的问题。 The linter returns me for something like:短绒使我返回类似的东西:

type outputFormat string

const (
    formatNone outputFormat = ""
    formatText              = "TEXT"
    formatJSON              = "JSON"
)

an error like:一个错误,如:

only the first constant in this group has an explicit type (staticcheck)只有该组中的第一个常量具有显式类型(staticcheck)
formatNone outputFormat = "" formatNone outputFormat = ""

But what's the problem about it?但它有什么问题呢? In https://go101.org/article/constants-and-variables.html they describe in chapter Autocomplete in constant declarations that incomplete constants will be recognized and filled.https://go101.org/article/constants-and-variables.html 中,他们在常量声明中的自动完成一章描述了不完整的常量将被识别和填充。

I did not find any reference which tells me to avoid using incomplete constant definitions.我没有找到任何参考资料告诉我避免使用不完整的常量定义。

Can somebody explain to me, what's the matter behind that?有人可以向我解释一下,这背后有什么问题吗?

As explained in staticcheck 's documentation for that check : staticcheck文档中所述

In a constant declaration such as the following: 在如下常量声明中:

 const ( First byte = 1 Second = 2 ) 

the constant Second does not have the same type as the constant First . Second 具有相同的类型常量First This construct shouldn't be confused with 此构造不应与

 const ( First byte = iota Second ) 

where First and Second do indeed have the same type. 其中FirstSecond确实具有相同的类型。 The type is only passed on when no explicit value is assigned to the constant. 仅当没有为常量指定显式值时,才传递类型。

When declaring enumerations with explicit values it is therefore important not to write 因此,在用显式值声明枚举时,重要的是不要写

 const ( EnumFirst EnumType = 1 EnumSecond = 2 EnumThird = 3 ) 

This discrepancy in types can cause various confusing behaviors and bugs. 类型上的差异会导致各种令人困惑的行为和错误。

In my case I solved the issue by including the type for all the enum items在我的情况下,我通过包含所有枚举项的类型解决了这个问题

type Verb string

const (
    DEL  Verb = "DEL"
    POST Verb = "POST"
    GET  Verb = "GET"
)

when I was puttig Verb only on the first enum (DEL) I got your same issue当我只在第一个枚举(DEL)上使用 puttig 动词时,我遇到了同样的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM