【发布时间】:2014-07-19 09:31:05
【问题描述】:
在 Go 中声明单个常量的首选方式是什么?
1)
const myConst
2)
const (
myConst
)
gofmt 接受这两种方式。两种方式都可以在 stdlib 中找到,虽然 1) 用得更多。
【问题讨论】:
标签: go constants conventions
在 Go 中声明单个常量的首选方式是什么?
1)
const myConst
2)
const (
myConst
)
gofmt 接受这两种方式。两种方式都可以在 stdlib 中找到,虽然 1) 用得更多。
【问题讨论】:
标签: go constants conventions
第二种形式主要用于对几个常量声明进行分组。
如果你只有一个常量,第一种形式就足够了。
const maxNanoSecondIntSize = 9
// Compression methods.
const (
Store uint16 = 0
Deflate uint16 = 8
)
这并不意味着您必须将所有常量归为一个const ():当您有由iota (successive integer) 初始化的常量时,每个块都很重要。
例如见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 加入the comments:
确实如此,但您会发现 iota 仅在 constant declaration 中使用,如果您需要多组连续整数常量,这将迫使您定义多个 const () 块。
【讨论】:
const () 块的示例。