在Golang中,是否可以在不创建String()函数的情况下获取枚举名称?

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

Is it possible to get Enum name without creating String() in Golang

问题

在Golang中,如果你不想创建func (TheEnum) String() string函数,是否有可能获取枚举名称?

  1. const (
  2. MERCURY = 1
  3. VENUS = iota
  4. EARTH
  5. MARS
  6. JUPITER
  7. SATURN
  8. URANUS
  9. NEPTUNE
  10. PLUTO
  11. )

或者是否有一种在运行时定义常量的方法?我找到了两种方法,一种是基于结构体的方法,另一种是基于字符串的方法,但这两种方法都需要我们额外输入每个标签一次(或者复制粘贴并引用,或者使用编辑器的宏)。

英文:

Is it possible to get Enum name without creating func (TheEnum) String() string in Golang?

  1. const (
  2. MERCURY = 1
  3. VENUS = iota
  4. EARTH
  5. MARS
  6. JUPITER
  7. SATURN
  8. URANUS
  9. NEPTUNE
  10. PLUTO
  11. )

or is there a way to define constants on the fly?
I found two ways struct-based and string-based, but both way make us retype each labels 1 more time (or copy-paste and quoting or using editor's macro)

答案1

得分: 21

据我所知,如果不显式将名称作为字符串输入,是无法实现这一点的。但是你可以使用标准工具包中的stringer工具来帮助你完成:

例如,给定以下代码片段:

  1. package painkiller
  2. type Pill int
  3. const (
  4. Placebo Pill = iota
  5. Aspirin
  6. Ibuprofen
  7. Paracetamol
  8. Acetaminophen = Paracetamol
  9. )

在相同的目录下运行以下命令:

  1. stringer -type=Pill

将会生成一个名为pill_string.go的文件,位于painkiller包中,其中包含以下定义:

  1. func (Pill) String() string

推荐在Go 1.4+中与go generate命令一起使用。

英文:

AFAIK, no you can't do that without explicitly typing the name as a string. But you can use the stringer tool from the standard tools package to do it for you:

>For example, given this snippet,
>
package painkiller
>
type Pill int
>
const (
Placebo Pill = iota
Aspirin
Ibuprofen
Paracetamol
Acetaminophen = Paracetamol
)

>running this command
>
stringer -type=Pill

>in the same directory will create the file pill_string.go, in package painkiller, containing a definition of
>
func (Pill) String() string

This is recommended to use with the go generate command of Go 1.4+.

答案2

得分: 1

作为补充:
在代码中使用以下注释可以帮助go generate知道要生成什么。
注意,在//go:generate之间没有空格。

  1. //go:generate stringer -type=Pill
  2. type Pill int
  3. const (
  4. Placebo Pill = iota
  5. Aspirin
  6. Ibuprofen
  7. Paracetamol
  8. Acetaminophen = Paracetamol
  9. )
英文:

As a supplement:
Use the following comment in the code can help go generate know what to generate.
Be careful, there is no space between // and go:generate

  1. //go:generate stringer -type=Pill
  2. type Pill int
  3. const (
  4. Placebo Pill = iota
  5. Aspirin
  6. Ibuprofen
  7. Paracetamol
  8. Acetaminophen = Paracetamol
  9. )

huangapple
  • 本文由 发表于 2014年11月28日 18:53:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/27187132.html
匿名

发表评论

匿名网友

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

确定