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

编程入门 行业动态 更新时间:2024-10-22 19:26:05
本文介绍了如何在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)中将接口类型用作模型?

本文发布于:2023-11-22 15:07:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617905.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   接口类型   模型   如何在   mgo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!