简体   繁体   中英

golangci-lint constant explicit type

I have a question about 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)
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.

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 :

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 . This construct shouldn't be confused with

 const ( First byte = iota Second ) 

where First and Second do indeed have the same type. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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