dongliugu8843 2014-09-25 13:14
浏览 52
已采纳

如何在mgo(Go)中将接口类型用作模型?

Suppose you have a workflow that consists of multiple embedded nodes of different types. Since nodes are of different types, I thought of using Golang interfaces here and came up with following:

type Workflow struct {
   CreatedAt time.Time
   StartedAt time.Time
   CreatedBy string
   Nodes []Node
}

type Node interface {
  Exec() (int, error)
}

type EmailNode struct {
   From string
   To string
   Subject string
   Body string
}

type TwitterNode struct {
   Tweet string
   Image []byte
}

func (n *EmailNode) Exec() (int, error){
   //send email
   return 0, nil
}

func (n *TwitterNode) Exec() (int, error) {
   //send tweet
   return 0, nil
}

These workflows are stored in MongoDB and I have sample seed data in it. Using mgo, when I try to find a workflow (given its ID):

w = &Workflow{}
collection.FindID(bson.ObjectIdHex(id)).One(w)

I get the error - value of type bson.M is not assignable to type Node.

It also feels a bit weird to me that how would mgo unmarshal embedded Node documents into a Go struct without any type information. May be I need to look at the problem from another point of view.

Any suggestions would be highly appreciated.

  • 写回答

2条回答 默认 最新

  • dongxiezhuo8852 2014-09-25 14:08
    关注

    You cannot use an interface in a document for the reason you noted. The decoder has no information about the type to create.

    One way to handle this is to define a struct to hold the type information:

    type NodeWithType struct {
       Node Node `bson:"-"`
       Type string
    }
    
    type Workflow struct {
       CreatedAt time.Time
       StartedAt time.Time
       CreatedBy string
       Nodes []NodeWithType
    }
    

    Implement the SetBSON function on this type. This function should decode the type string, create a value of the correct type based on that string and unmarshal to that value.

    func (nt *NodeWithType) SetBSON(r bson.Raw) error {
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来