我有以下结构...
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,并在string和bson.ObjectId之间转换它的类型。然后遍历每个map字段并执行相同的操作。这感觉像是一个低效的解决方案。
所以我尝试使用反射来在两个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
}我不能只是手动重新分配字段,因为我希望检测结构字段上的映射并递归地对它们执行此函数,但嵌入的结构上的字段不会相同。
希望这是有意义的!
发布于 2017-07-23 04:16:30
我认为编写您自己的转换器可能更好,因为您总是会有一些现有的libs\工具无法涵盖的情况。
我最初的实现是这样的:basic impl of structs merger
https://stackoverflow.com/questions/45254738
复制相似问题