在Go语言中实现枚举类型

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

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

代码示例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package enum

import (
"bytes"
"encoding/json"
)

// NodeState asd
type NodeState int

const (
// Uninitialized asd
Uninitialized NodeState = iota
// Initialized asd
Initialized
// Synchronized represents the task is complete
Synchronized
// Errorred represents the task has encountered a problem and is no longer running
Errorred
)

func (s NodeState) String() string {
return toString[s]
}

var toString = map[NodeState]string{
Uninitialized: "Uninitialized",
Initialized: "Initialized",
Synchronized: "Synchronized",
Errorred: "Errorred",
}

var toID = map[string]NodeState{
"Uninitialized": Uninitialized,
"Initialized": Initialized,
"Synchronized": Synchronized,
"Errorred": Errorred,
}

func (s NodeState) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
buffer.WriteString(toString[s])
buffer.WriteString(`"`)
return buffer.Bytes(), nil
}

func (s *NodeState) UnmarshalJSON(b []byte) error {
var j string
err := json.Unmarshal(b, &j)
if err != nil {
return err
}
*s = toID[j]
return nil
}