合并两个不同类型的相似结构

Merging two similar structs of different types

我有以下结构...

type Menu struct {
    Id          string     `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"`
    Name        string     `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"`
    Description string     `protobuf:"bytes,3,opt,name=description" json:"description,omitempty"`
    Mixers      []*Mixer   `protobuf:"bytes,4,rep,name=mixers" json:"mixers,omitempty"`
    Sections    []*Section `protobuf:"bytes,5,rep,name=sections" json:"sections,omitempty"`
}

还有……

type Menu struct {
    ID          bson.ObjectId `json:"id" bson:"_id"`
    Name        string        `json:"name" bson:"name"`
    Description string        `json:"description" bson:"description"`
    Mixers      []Mixer       `json:"mixers" bson:"mixers"`
    Sections    []Section     `json:"sections" bson:"sections"`
}

我基本上需要在两种结构类型之间进行转换,我曾尝试使用 mergo,但它只能合并可分配给彼此的结构。到目前为止,我唯一的解决方案是遍历每个结构,通过重新分配 ID 并在字符串和 bson.ObjectId 之间转换其类型来转换 ID。然后遍历每个映射字段并执行相同的操作。这感觉像是一个低效的解决方案。

所以我尝试使用反射来更通用地在两个 ID 之间进行转换。但我不知道如何有效地合并所有自动匹配的其他字段,所以我只能担心 ID 类型之间的转换。

这是我目前的代码...

package main

import (
    "fmt"
    "reflect"

    "gopkg.in/mgo.v2/bson"
)

type Sub struct {
    Id bson.ObjectId
}

type PbSub struct {
    Id string
}

type PbMenu struct {
    Id   string
    Subs []PbSub
}

type Menu struct {
    Id   bson.ObjectId
    Subs []Sub
}

func main() {
    pbMenus := []*PbMenu{
        &PbMenu{"1", []PbSub{PbSub{"1"}}},
        &PbMenu{"2", []PbSub{PbSub{"1"}}},
        &PbMenu{"3", []PbSub{PbSub{"1"}}},
    }

    newMenus := Serialise(pbMenus)
    fmt.Println(newMenus)
}

type union struct {
    PbMenu
    Menu
}

func Serialise(menus []*PbMenu) []Menu {
    newMenus := []Menu{}
    for _, v := range menus {
        m := reflect.TypeOf(*v)
        fmt.Println(m)
        length := m.NumField()
        for i := 0; i < length; i++ {
            field := reflect.TypeOf(v).Field(i)
            fmt.Println(field.Type.Kind())
            if field.Type.Kind() == reflect.Map {
                fmt.Println("is map")
            }
            if field.Name == "Id" && field.Type.String() == "string" {

                // Convert ID type
                id := bson.ObjectId(v.Id)
                var dst Menu
                dst.Id = id

                // Need to merge other matching struct fields

                newMenus = append(newMenus, dst)
            }
        }
    }
    return newMenus
}

我不能只是手动重新分配字段,因为我希望检测结构字段上的映射并递归地对它们执行此功能,但嵌入式结构上的字段不会相同.

希望这是有道理的!

我认为编写自己的转换器可能更好,因为您总会遇到一些现有 libs\tools 未涵盖的情况。

我最初的实现是这样的:basic impl of structs merger