go - 在 Go 中有没有办法将结构映射转换为结构切片
问题描述
我必须将结构映射转换为 Golang 中的结构切片,即下面指定的源结构到目标结构。
// Source
var source map[string]Category
type Category struct {
A int
SubCategory map[string]SubCategory
}
type SubCategory struct {
B int
C string
}
// Target
var target []OldCategory
type OldCategory struct {
OldA int `mapstructure:"A"`
OldSubCategory []OldSubCategory
}
type OldSubCategory struct {
OldB int `mapstructure:"B"`
OldC string `mapstructure:"C"`
}
我指的是地图结构包(“github.com/mitchellh/mapstructure”)。从源转换为目标的一种方法是在源实例中迭代所有子类别,然后是类别,并使用 mapstructure.Decode() 单独转换每个子类别。
有没有使用mapstructure包的直接方法,其中我使用NewDecoder和DecoderConfig.DecodeHook创建一个自定义解码器钩子,每当我遇到源作为结构的映射和目标作为结构的切片时,我都会在DecodeHookFunc函数中处理它。
mapstructure 的相关文档 https://godoc.org/github.com/mitchellh/mapstructure#NewDecoder
解决方案
使用嵌套的 for 循环:
for _, c := range source {
oc := OldCategory{OldA: c.A}
for _, sc := range c.SubCategory {
oc.OldSubCategory = append(oc.OldSubCategory, OldSubCategory{OldB: sc.B, OldC: sc.C})
}
target = append(target, oc)
}
推荐阅读
- typescript - 无法使用 Typescript 和 Puppeteer 部署 firebase 功能
- javascript - 匹配用户算法
- python - Scipy curvefit RuntimeError:未找到最佳参数。测试并避免错误消息
- android - 如果从数据库接收空数据显示(Toast.makeText)android,如何进行截击
- delphi - 从 TPanel 中删除按钮,Firemonkey 版
- c# - C#:这个语句在做什么?dynObj.@switch == 1 ?真假
- java - 如何使用链表实现退出堆栈?
- java - 无法通知依赖解析侦听器
- silverstripe - 由 js 填充的 SilverStripe DropdownField - [值] 不是有效选项
- excel - COUNTIFS 函数跨多个工作表工作