为整个 const 块设置类型

Set type for entire const block

我有自定义数据类型

type Custom string

还有一个常量块

const (
    Item1 = "placeholder"
    ...
    Item10 = "placeholder"
)

是否可以为 const 块中的每个项目设置自定义类型,而不必将其放在每个条目中?

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")
)