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

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

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

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 &quot;fmt&quot;

const (
	I1 = 1 &lt;&lt; iota
	I2
	I3
	ILen int = iota
)

const (
	X1       = &quot;A&quot;
	X2       = &quot;B&quot;
	X3       = &quot;C&quot;
	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.

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:

确定