Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 687
xged Avatar asked Feb 13 '23 11:02

xged


1 Answers

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.

like image 87
VonC Avatar answered Mar 08 '23 01:03

VonC