在 Go 中声明单个常量的首选方法是什么?
1)
const myConst
2)
const (
myConst
)
gofmt
接受这两种方式。 stdlib 中均有这两种方式,但 1) 用得更多。
最佳答案
第二种形式主要是对几个常量声明进行分组。
如果你只有一个常量,第一种形式就足够了。
const maxNanoSecondIntSize = 9
// Compression methods.
const (
Store uint16 = 0
Deflate uint16 = 8
)
这并不意味着您必须将所有 常量分组到一个const ()
中:当您有由iota (successive integer) 初始化的常量时,每个 block 都很重要。
参见例如 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 :
it can also be done with
import
,type
,var
, and more than once.
这是真的,但你会发现 iota
只在 constant declaration 中使用,如果您需要多组连续的整数常量,这将迫使您定义多个 const ()
block 。
关于戈朗 : declare a single constant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24838846/