xged
xged

Reputation: 1233

Golang: declare a single constant

Which is the preferred way to declare a single constant in Go?

1)

const myConst

2)

const (
        myConst
)

Both ways are accepted by gofmt. Both ways are found in stdlib, though 1) is used more.

Upvotes: 4

Views: 1772

Answers (1)

VonC
VonC

Reputation: 1324248

The second form is mainly for grouping several constant declarations.

If you have only one constant, the first form is enough.

for instance archive/tar/reader.go:

const maxNanoSecondIntSize = 9

But in archive/zip/struct.go:

// Compression methods.
const (
        Store   uint16 = 0
        Deflate uint16 = 8
)

That doesn't mean you have to group all constants in one const (): when you have constants initialized by iota (successive integer), each block counts.
See for instance cmd/yacc/yacc.go

// flags for state generation
const (
    DONE = iota
    MUSTDO
    MUSTLOOKAHEAD
)

// flags for a rule having an action, and being reduced
const (
    ACTFLAG = 1 << (iota + 2)
    REDFLAG
)

dalu adds in the comments:

it can also be done with import, type, var, and more than once.

It is true, but you will find iota only use in a constant declaration, and that would force you to define multiple const () blocks if you need multiple sets of consecutive integer constants.

Upvotes: 8

Related Questions