Golang:声明一个单一常量

huangapple go评论87阅读模式
英文:

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

第二种形式主要用于将多个常量声明分组。

如果只有一个常量,第一种形式就足够了。

例如archive/tar/reader.go

const maxNanoSecondIntSize = 9

但在archive/zip/struct.go中:

// 压缩方法
const (
    Store   uint16 = 0
    Deflate uint16 = 8
)

这并不意味着你必须将所有常量都放在一个const ()中:当你有通过iota(连续整数)初始化的常量时,每个块都计数。
例如cmd/yacc/yacc.go

// 状态生成的标志
const (
    DONE = iota
    MUSTDO
    MUSTLOOKAHEAD
)

// 规则具有动作和被规约的标志
const (
    ACTFLAG = 1 << (iota + 2)
    REDFLAG
)

dalu评论中补充道:

> 这也可以通过importtypevar等方式实现,并且可以多次使用。

这是正确的,但你会发现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 &lt;&lt; (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.

huangapple
  • 本文由 发表于 2014年7月19日 17:31:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/24838846.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定