首页 > 解决方案 > 在 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

标签: gostructgo-map

解决方案


使用嵌套的 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)
}

推荐阅读