如何在mgo(Go)中将接口类型用作模型? [英] How to use interface type as a model in mgo (Go)?

查看:97
本文介绍了如何在mgo(Go)中将接口类型用作模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您的工作流由多个不同类型的嵌入式节点组成.由于节点的类型不同,因此我想到在这里使用Golang接口,并提出以下建议:

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
}

这些工作流存储在MongoDB中,并且我有示例种子数据.当我尝试查找工作流程(根据其ID)时,使用mgo:

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)

我得到了错误-bson.M类型的值不能分配给Node类型.

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

让我感到有些奇怪的是,如何在没有任何类型信息的情况下将嵌入式Node文档解组到Go结构中.可能我需要从另一个角度来看问题.

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.

任何建议将不胜感激.

推荐答案

由于提到的原因,您不能在文档中使用接口.解码器没有有关要创建的类型的信息.

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
}

在此类型上实现SetBSON函数.此函数应解码类型字符串,根据该字符串创建正确类型的值,然后解组为该值.

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 {
}

这篇关于如何在mgo(Go)中将接口类型用作模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆