戈朗 : declare a single constant

标签 go constants conventions

在 Go 中声明单个常量的首选方法是什么?

1)

const myConst

2)

const (
        myConst
)

gofmt 接受这两种方式。 stdlib 中均有这两种方式,但 1) 用得更多。

最佳答案

第二种形式主要是对几个常量声明进行分组。

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

例如archive/tar/reader.go :

const maxNanoSecondIntSize = 9

但是在archive/zip/struct.go :

// 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/

相关文章:

python - 如何使用不会引起 PEP 警告的选项卡

java - 是否应该在 Java 中避免像 "if (condition) if (condition) ..."这样的多个 if 语句?

api - 编写从 Lua 调用的 API - 基于 0 还是 1?

go - 如何将动态 YAML 解码为 Go 中字符串 -> 字符串 -> 结构的映射?

外部类型问题的 JSON 序列化 - 将 map[string]interface{} 项转换为 int

go - 在 Go 中测量 FLOPS

python - 为什么 True 和 False 在 Python 2 中仍然可以修改?

json - Go中如何自定义JSON编码输出?

c++ - 数组声明中 const int 和 int 之间的区别?

c++ - 如果从未通过它们进行修改,是否允许对实际 const 对象的引用进行 const 转换?