How do I do enums in golang?

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

How do I do enums in golang?

问题

我可以帮你翻译代码部分,以下是翻译的结果:

我有以下代码

    const (
      BlahFoo = 1 << iota
      MooFoo
    )

然后

    type Cluster struct {
      a  int
      b  int
    }

我想要确保 Cluster.a 只能是 BlahFoo  MooFoo

我该如何实现这个要求
英文:

I have

const (
  BlahFoo = 1 &lt;&lt; iota
  MooFoo
)

then

type Cluster struct {
  a  int
  b  int
}

I want Cluster.a to only be BlahFoo or MooFoo

How do I enforce that?

答案1

得分: 9

type FooEnum int

const (
  BlahFoo FooEnum = 1 << iota
  MooFoo
)

type Cluster struct {
  a FooEnum
  b int
}
类型 FooEnum int

const (
  BlahFoo FooEnum = 1 << iota
  MooFoo
)

类型 Cluster struct {
  a FooEnum
  b int
}
英文:
type FooEnum int

const (
  BlahFoo FooEnum = 1 &lt;&lt; iota
  MooFoo
)

type Cluster struct {
  a FooEnum
  b int
}

huangapple
  • 本文由 发表于 2015年3月17日 02:00:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/29083806.html
匿名

发表评论

匿名网友

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

确定