在我的Go代码中,我有以下情况:
type Operator int
const (
UNKNOWN Operator = iota
EQUALS
CONTAINS
BETWEEN
DISTANCE
)
type Filter struct {
Field string `json:"field"`
Operator Operator `json:"operator"`
Values []string `json:"values"`
}
Run Code Online (Sandbox Code Playgroud)
我期望的JSON看起来如下:
{
"operator": "EQUALS",
"field": "name",
"values": [ "John", "Doe" ]
}
Run Code Online (Sandbox Code Playgroud)
我可以创建一个映射,以便json.Unmarshal在Filter结构中设置正确的运算符常量吗?我知道Unmarshaler接口,但我认为这不能真正用于常量值.
我真的希望将常量保留在我的代码中,因为当我传递它时,这很好地强制执行类型检查和一致性.