可以在Golang中创建String()来获取枚举名称 [英] Is it possible to get Enum name without creating String() in Golang

查看:1347
本文介绍了可以在Golang中创建String()来获取枚举名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Golang中创建 func(TheEnum)String()string 来获取枚举名称?

  const(
MERCURY = 1
VENUS = iota
EARTH
MARS
JUPITER
SATURN
URANUS
NEPTUNE
PLUTO

还是有一种方式在飞行中定义常量?
我发现两种方式 struct 字符串,但这两种方式使我们每次重新输入每个标签1次(或复制粘贴)引用或使用编辑器的宏)

解决方案

AFAIK,没有明确地输入名称作为字符串,你不可以这样做。但您可以使用 stringer 工具从标准工具包中为您做:


例如,给定此代码段,

  package painkiller 

type Pill int

const(
安慰剂丸= iota
阿司匹林
布洛芬
对乙酰氨基酚
对乙酰氨基酚=扑热息痛

运行此命令

  stringer -type = Pill 
/ pre>

在同一个目录中将创建文件pill_string.go,在包中止痛药包含

  func(Pill)String()string 


建议与Go 1.4 +的 go生成命令配合使用。


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

const (
 MERCURY = 1
 VENUS = iota
 EARTH
 MARS
 JUPITER
 SATURN
 URANUS
 NEPTUNE
 PLUTO
)

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)

解决方案

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+.

这篇关于可以在Golang中创建String()来获取枚举名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆