我想在 go 中将 xml 属性解析为 iota 枚举类型 (int)。
下面您可以看到我尝试过的方法,但这不起作用,因为无法获取枚举变量的地址。
type EnumType int
const (
EnumUnknown EnumType = iota
EnumFoo
EnumBar
)
func (E *EnumType) UnmarshalXMLAttr(attr xml.Attr) error {
switch attr.Value {
case "foo":
E = &EnumFoo
case "bar":
E = &EnumBar
default:
E = &EnumUnknown
}
return nil
}
// Example of how the unmarshal could be called:
type Tag struct {
Attribute EnumType `xml:"attribute,attr"`
}
func main() {
tag := &Tag{}
xml.Unmarshal([]byte("<tag attribute=\"foo\"/>"), tag)
}
还有其他方法可以使 UnmarshalXMLAttr
与 int 类型一起工作吗?
更新:我知道我可以通过将 UnmarshalXML
方法添加到 Tag 来解决这个问题,但我想尽可能避免这种情况,因为我有很多不同的标签,它们具有很多不同的属性,但只有一个很少有自定义类型的属性。因此,为每个标记实现 UnmarshalXML
方法并不是首选。
最佳答案
我通过将 int 包装在一个结构中解决了这个问题。
type EnumType int
const (
EnumUnknown EnumType = iota
EnumFoo
EnumBar
)
type EnumContainer struct {
Value EnumType
}
func (E *EnumContainer) UnmarshalXMLAttr(attr xml.Attr) error {
switch attr.Value {
case "foo":
E.Value = EnumFoo
case "bar":
E.Value = EnumBar
default:
E.Value = EnumUnknown
}
return nil
}
// Example of how the unmarshal could be called:
type Tag struct {
Attribute EnumContainer `xml:"attribute,attr"`
}
func main() {
tag := &Tag{}
xml.Unmarshal([]byte("<tag attribute=\"foo\"/>"), tag)
是否有“更优雅”的方式,或者我应该对我现在拥有的感到满意?
关于xml - 如何在 go 中解码 xml 枚举属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56317781/