【发布时间】:2018-09-11 10:46:51
【问题描述】:
我正在尝试借助 mapstructure 库将地图解码为结构类型。如果我使用普通变量进行解码,它可以解码,但如果我传递 struct 字段,它不会解码地图:
package main
import (
"github.com/mitchellh/mapstructure"
)
type Person struct {
Name string
}
type Bundle struct {
Name string
Struct interface{}
}
func main() {
p_map := map[string]string{
"Name": "John",
}
p := Person{}
mapstructure.Decode(p_map, &p)
print(p.Name) // shows name John
b := Bundle{
"person"
Person{},
}
mapstructure.Decode(p_map, &b.Struct)
print(b.Struct.(Person).Name) // Does not show any name. Blank
}
您能否澄清一下我是否为地图解码传递了错误的存储空间,或者这只是地图结构的限制,我无法将地图解码为结构字段?谢谢!
UPD
如果我对我需要使用这种流程的实际原因不够清楚,我很抱歉:
我向不同的资源发送 HTTP 请求并获取具有不同字段的各种对象,因此最初我将它们收集为interface{}。获得特定资源对象后,我需要将其转换为特定结构(在我的示例中为Person),因此我使用mapstructure.decode() 函数。
由于我有各种以不同结构解码的对象,我想创建一个循环以避免代码重复。我想做的是创建一个具有不同结构的切片,例如:
bundles := []Bundle{
{"person", Person{}}
{"employee", Employee{}}
...
}
然后循环解码对象:
for bundle := range bundles {
// map_storage contains different type maps that are going to be decoded into struct and key for the specific object is bundle name
mapstructure.Decode(maps_storage[bundle.Name], &bundle.Struct)
// bundle.Struct blank, but I expect that it is filled as in the example below
}
【问题讨论】:
标签: go