go - 设置整个const block 的类型

标签 go types constants

我有一个自定义数据类型type Custom string还有一个const块

const (
    Item1 = "placeholder"
    ...
    Item10 = "placeholder"
)
是否可以将const块中的每个项目都设置为Custom类型,而不必将其放置在每个条目中?

最佳答案

Spec: Constant declarations:

ConstDecl      = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
ConstSpec      = IdentifierList [ [ Type ] "=" ExpressionList ] .

常量声明是一系列常量规范,其中每个规范都包含可选类型。
可以利用的一件事是:

Within a parenthesized const declaration list the expression list may be omitted from any but the first ConstSpec. Such an empty list is equivalent to the textual substitution of the first preceding non-empty expression list and its type if any. Omitting the list of expressions is therefore equivalent to repeating the previous list. The number of identifiers must be equal to the number of expressions in the previous list. Together with the iota constant generator this mechanism permits light-weight declaration of sequential values...


因此,例如在下面的示例中,Item1Item2的类型都将为Custom:
const (
    Item1 Custom = "v1"
    Item2
)
这里的问题是Item1Item2将具有相同的"v1"值。除非您在表达式中使用iota,否则这实际上没有用。
仅指定一次类型的一种方法是在值之前列出标识符:
const (
    Item1, Item2 Custom = "v1", "v2"
)
在上面的示例中,Item1Item2均为Custom类型,请在Go Playground上尝试使用。这里的缺点是标识符可能会“远离”它的值,这比在单独的行上列出它们的可读性差:
const (
    Item1 Custom = "v1"
    Item2 Custom = "v2"
)
或者,您可以使用键入的常量值将“类型”移至表达式:
const (
    Item1 = Custom("v1")
    Item2 = Custom("v2")
)

关于go - 设置整个const block 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64826695/

相关文章:

c++ - 是否可以描述一些原始类型的子类型?

haskell - 类型文字用法

python - 返回属性名称和类型值的字典

json - Go:JSON 编码嵌套结构;错误地省略了外部字段

function - 如何从Go中的用户输入中打印出函数中的值

concurrency - Go 中的增量运算符在 x86 上是原子的吗?

Golang : . Scan() 忽略类型模板.HTML

c - ANCI C (C90) : Can const be changed?

perl - 如何使用 Perl 模块中的常量?

c++ - "const"在 C 和 C++ 中有何不同?