[英]Couldn't unmarshal xml to a dynamically created struct using reflection in Golang
這是我解析 xml 的代碼。 在 function 的末尾,我應該在值切片中包含結構的字段值。
func FindAttrs(attrs []Tag, errorChan chan<- error) {
var tableFields []reflect.StructField
for _, v := range attrs {
tableFields = append(tableFields, reflect.StructField{
Name: strings.Title(v.Name),
Type: reflect.TypeOf(""),
Tag: reflect.StructTag(fmt.Sprintf(`xml:"%v,attr"`, v.Name)),
Offset: 0,
PkgPath: "utility",
Index: nil,
Anonymous: false,
})
}
unmarshalStruct := reflect.Zero(reflect.StructOf(tableFields))
err := xml.Unmarshal(ReadBytes(errorChan), &unmarshalStruct)
HandleError(err, "Error parse config", false, errorChan)
values := make([]interface{}, unmarshalStruct.NumField())
for i := 0; i < unmarshalStruct.NumField(); i++ {
values[i] = unmarshalStruct.Field(0).Interface()
}
}
但是,它會因以下消息而恐慌:
reflect.Value.Interface: cannot return value obtained from unexported field or method
我稱之為:
utility.FindAttrs([]utility.Tag{
{"name", reflect.String}, {"isUsed", reflect.String},
}, errorChan)
而我的 xml 是<configuration name="mur" isUsed="mur"/>
需要創建一個指向結構而不是值的指針並將指針的值傳遞給Interface()
而不是它本身。
var tableFields []reflect.StructField
for _, v := range attrs {
tableFields = append(tableFields, reflect.StructField{
Name: strings.Title(v.Name),
Type: reflect.TypeOf(""),
Tag: reflect.StructTag(fmt.Sprintf(`xml:"%v,attr"`, v.Name)),
})
}
rv := reflect.New(reflect.StructOf(tableFields)) // initialize a pointer to the struct
v := rv.Interface() // get the actual value
err := xml.Unmarshal([]byte(`<configuration name="foo" isUsed="bar"/>`), v)
if err != nil {
panic(err)
}
rv = rv.Elem() // dereference the pointer
values := make([]interface{}, rv.NumField())
for i := 0; i < rv.NumField(); i++ {
values[i] = rv.Field(i).Interface()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.