How to use interface type as a model in mgo (Go)?

后端 未结 2 1982
说谎
说谎 2021-01-03 04:18

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 ca

2条回答
  •  耶瑟儿~
    2021-01-03 04:57

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

提交回复
热议问题