英文:
Golang: declare a single constant
问题
在Go语言中,声明单个常量的首选方式是哪种?
const myConst
const (
myConst
)
这两种方式都被gofmt
接受。这两种方式都可以在stdlib中找到,尽管1)的使用更为广泛。
英文:
Which is the preferred way to declare a single constant in Go?
1)
const myConst
const (
myConst
)
Both ways are accepted by gofmt
. Both ways are found in stdlib, though 1) is used more.
答案1
得分: 8
第二种形式主要用于将多个常量声明分组。
如果只有一个常量,第一种形式就足够了。
const maxNanoSecondIntSize = 9
// 压缩方法
const (
Store uint16 = 0
Deflate uint16 = 8
)
这并不意味着你必须将所有常量都放在一个const ()
中:当你有通过iota(连续整数)初始化的常量时,每个块都计数。
例如cmd/yacc/yacc.go
// 状态生成的标志
const (
DONE = iota
MUSTDO
MUSTLOOKAHEAD
)
// 规则具有动作和被规约的标志
const (
ACTFLAG = 1 << (iota + 2)
REDFLAG
)
> 这也可以通过import
、type
、var
等方式实现,并且可以多次使用。
这是正确的,但你会发现iota
只在常量声明中使用,如果你需要多组连续的整数常量,这将迫使你定义多个const ()
块。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论