gpt4 book ai didi

xml - 使用 Go 将 XML 解码为接口(interface)类型?

转载 作者:IT王子 更新时间:2023-10-29 02:05:57 24 4
gpt4 key购买 nike

是否可以使用 Go 1.3 将 XML 解码为接口(interface)类型?

例如,如果结构看起来像这样(简化):

type Field interface { ... }

// DataField and ControlField satisfy Field interface
type DataField struct { ... } // <- One concrete type, with XML tags
type ControlField struct { ... } // <- Another concrete type, with XML tags


type Record struct {
Fields []Field // <- Field is an interface
}

...
// we want to decode into a record, e.g.
var record Record
decoder.DecodeElement(&record, &se)
...

据我所知,可以用具体类型解码 XML,例如:

type Record struct {
ControlFields []ControlField // <- Using concrete type works
DataFields []DataField // <- Using concrete type works
}

但是接口(interface)类型失败了,尽管使用正确的 XML 标记对实现进行了注释。

有关可运行的示例,请参阅 http://play.golang.org/p/tPlw4Y74ttgist .

最佳答案

从看the codeencoding/xml 包中,接口(interface)类型似乎被跳过了:

...

switch v := val; v.Kind() {

case reflect.Interface:
// TODO: For now, simply ignore the field. In the near
// future we may choose to unmarshal the start
// element on it, if not nil.
return p.Skip()

...

Go 版本:1.3。

关于xml - 使用 Go 将 XML 解码为接口(interface)类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25269171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com