Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Enums 是否可以在Golang中不创建String()而获取枚举名_Enums_Go - Fatal编程技术网

Enums 是否可以在Golang中不创建String()而获取枚举名

Enums 是否可以在Golang中不创建String()而获取枚举名,enums,go,Enums,Go,在Golang中不创建func(TheEnum)String()字符串就可以获取枚举名吗 const ( MERCURY = 1 VENUS = iota EARTH MARS JUPITER SATURN URANUS NEPTUNE PLUTO ) 或者有没有一种方法可以动态定义常量? 我发现有两种方法,一种是基于,另一种是基于,但这两种方法都会使我们重新键入每个标签1次(或者复制粘贴和引用,或者使用编辑器的宏)AFAIK,不,如果不将名称显式键入为字符串,您就无法做到这

在Golang中不创建
func(TheEnum)String()字符串
就可以获取枚举名吗

const (
 MERCURY = 1
 VENUS = iota
 EARTH
 MARS
 JUPITER
 SATURN
 URANUS
 NEPTUNE
 PLUTO
)
或者有没有一种方法可以动态定义常量?
我发现有两种方法,一种是基于,另一种是基于,但这两种方法都会使我们重新键入每个标签1次(或者复制粘贴和引用,或者使用编辑器的宏)

AFAIK,不,如果不将名称显式键入为字符串,您就无法做到这一点。但您可以使用标准工具包中的来为您执行此操作:

例如,给定这个片段

package painkiller

type Pill int

const (
    Placebo Pill = iota
    Aspirin
    Ibuprofen
    Paracetamol
    Acetaminophen = Paracetamol
)
运行此命令

stringer -type=Pill
在同一目录中,将在painkiller包中创建文件pill_string.go,其中包含

func (Pill) String() string
建议与go 1.4+的
go generate
命令一起使用。

作为补充:
在代码中使用以下注释可以帮助
go generate
知道要生成什么。 小心,
/
go:generate

//go:generate stringer -type=Pill
type Pill int

const (
    Placebo Pill = iota
    Aspirin
    Ibuprofen
    Paracetamol
    Acetaminophen = Paracetamol
)
还要注意的是。