英文:
Is there a way to count total number of items defined in Enum?
问题
我正在尝试计算在Go语言中定义的枚举(iota)中的项数,但我不确定如何做到这一点。
英文:
I am trying to count the number of items defined in my enum (iota) in Go, but I am unsure of how to do that.
答案1
得分: 8
例如,ILen
和 XLen
,
package main
import "fmt"
const (
I1 = 1 << iota
I2
I3
ILen int = iota
)
const (
X1 = "A"
X2 = "B"
X3 = "C"
XLen int = iota
)
func main() {
fmt.Println(I1, I2, I3, ILen)
fmt.Println(X1, X2, X3, XLen)
}
输出结果为:
1 2 4 3
A B C 3
在常量声明中,预声明的标识符 iota
表示连续的无类型整数常量。它的值是该常量声明中相应 ConstSpec
的索引,从零开始。
英文:
For example, ILen
and XLen
,
package main
import "fmt"
const (
I1 = 1 << iota
I2
I3
ILen int = iota
)
const (
X1 = "A"
X2 = "B"
X3 = "C"
XLen int = iota
)
func main() {
fmt.Println(I1, I2, I3, ILen)
fmt.Println(X1, X2, X3, XLen)
}
https://go.dev/play/p/krBVid3jLNq
1 2 4 3
A B C 3
> The Go Programming Language Specification
>
> Iota
>
> Within a constant declaration, the predeclared identifier iota
represents successive untyped integer constants. Its value is the index of the respective ConstSpec in that constant declaration, starting at zero.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论