我有一个自定义数据类型type Custom string
还有一个const块
const (
Item1 = "placeholder"
...
Item10 = "placeholder"
)
是否可以将const块中的每个项目都设置为Custom类型,而不必将其放置在每个条目中?
最佳答案
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 theiota
constant generator this mechanism permits light-weight declaration of sequential values...
因此,例如在下面的示例中,
Item1
和Item2
的类型都将为Custom
:const (
Item1 Custom = "v1"
Item2
)
这里的问题是Item1
和Item2
将具有相同的"v1"
值。除非您在表达式中使用iota
,否则这实际上没有用。仅指定一次类型的一种方法是在值之前列出标识符:
const (
Item1, Item2 Custom = "v1", "v2"
)
在上面的示例中,Item1
和Item2
均为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/