在Go语言中实现枚举类型

2 minute read

可能因为我是从Java世界中来,在使用Go语言的时候,当需要一个ENUM的时候,没有很好的办法,于是我就做了一些功课。

Go语言中没有枚举这个类型,要实现枚举类型,可以用两个map来做lookup,这样可以快速的在enum和string之间转换。 同时考虑到serialize和deseriazlie JSON的需求,提供 MarshalJSON 和 UnmarshalJSON 这两个类型方法

代码示例如下

 1package enum
 2
 3import (
 4	"bytes"
 5	"encoding/json"
 6)
 7
 8// NodeState asd
 9type NodeState int
10
11const (
12	// Uninitialized asd
13	Uninitialized NodeState = iota
14	// Initialized asd
15	Initialized
16	// Synchronized represents the task is complete
17	Synchronized
18	// Errorred represents the task has encountered a problem and is no longer running
19	Errorred
20)
21
22func (s NodeState) String() string {
23	return toString[s]
24}
25
26var toString = map[NodeState]string{
27	Uninitialized: "Uninitialized",
28	Initialized:   "Initialized",
29	Synchronized:  "Synchronized",
30	Errorred:      "Errorred",
31}
32
33var toID = map[string]NodeState{
34	"Uninitialized": Uninitialized,
35	"Initialized":   Initialized,
36	"Synchronized":  Synchronized,
37	"Errorred":      Errorred,
38}
39
40func (s NodeState) MarshalJSON() ([]byte, error) {
41	buffer := bytes.NewBufferString(`"`)
42	buffer.WriteString(toString[s])
43	buffer.WriteString(`"`)
44	return buffer.Bytes(), nil
45}
46
47func (s *NodeState) UnmarshalJSON(b []byte) error {
48	var j string
49	err := json.Unmarshal(b, &j)
50	if err != nil {
51		return err
52	}
53	*s = toID[j]
54	return nil
55}
56