xge*_*ged 3 const conventions go
哪个是在Go中声明单个常量的首选方法?
1)
const myConst
Run Code Online (Sandbox Code Playgroud)
2)
const (
myConst
)
Run Code Online (Sandbox Code Playgroud)
两种方式都被接受gofmt.两种方式都可以在stdlib中找到,尽管1)使用得更多.
第二种形式主要用于对几个常量声明进行分组.
如果你只有一个常量,那么第一个形式就足够了.
const maxNanoSecondIntSize = 9
Run Code Online (Sandbox Code Playgroud)
// Compression methods.
const (
Store uint16 = 0
Deflate uint16 = 8
)
Run Code Online (Sandbox Code Playgroud)
这并不意味着您必须将所有常量组合在一起const ():当您使用iota(连续整数)初始化常量时,每个块都会计数.
例如,见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
)
Run Code Online (Sandbox Code Playgroud)
确实如此,但您会发现iota仅在常量声明中使用,const ()如果您需要多组连续的整数常量,这将强制您定义多个块.
| 归档时间: |
|
| 查看次数: |
666 次 |
| 最近记录: |