有没有一种方法可以计算枚举中定义的总项目数?

huangapple go评论121阅读模式
英文:

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

例如,ILenXLen

  1. package main
  2. import "fmt"
  3. const (
  4. I1 = 1 << iota
  5. I2
  6. I3
  7. ILen int = iota
  8. )
  9. const (
  10. X1 = "A"
  11. X2 = "B"
  12. X3 = "C"
  13. XLen int = iota
  14. )
  15. func main() {
  16. fmt.Println(I1, I2, I3, ILen)
  17. fmt.Println(X1, X2, X3, XLen)
  18. }

输出结果为:

  1. 1 2 4 3
  2. A B C 3

在常量声明中,预声明的标识符 iota 表示连续的无类型整数常量。它的值是该常量声明中相应 ConstSpec 的索引,从零开始。

英文:

For example, ILen and XLen,

  1. package main
  2. import &quot;fmt&quot;
  3. const (
  4. I1 = 1 &lt;&lt; iota
  5. I2
  6. I3
  7. ILen int = iota
  8. )
  9. const (
  10. X1 = &quot;A&quot;
  11. X2 = &quot;B&quot;
  12. X3 = &quot;C&quot;
  13. XLen int = iota
  14. )
  15. func main() {
  16. fmt.Println(I1, I2, I3, ILen)
  17. fmt.Println(X1, X2, X3, XLen)
  18. }

https://go.dev/play/p/krBVid3jLNq

  1. 1 2 4 3
  2. 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.

huangapple
  • 本文由 发表于 2023年2月22日 11:35:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75528015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定