How to Use an Interface as a Model in mgo (Go)
When dealing with workflows that contain multiple embedded nodes of different types, leveraging Go interfaces is a common approach. However, it presents a challenge when attempting to unmarshal these documents using mgo.
To address this issue, you cannot directly include an interface within a document. This is because the decoder lacks the necessary type information to create the appropriate instance.
A viable solution involves creating a wrapper struct to store both the actual node and its type:
type NodeWithType struct { Node Node `bson:"-"` Type string } type Workflow struct { CreatedAt time.Time StartedAt time.Time CreatedBy string Nodes []NodeWithType }
To complete the setup, you must implement the SetBSON function on NodeWithType. This function will decode the type string, instantiate the correct node type based on that string, and then unmarshal the document into the newly created instance. Implementing SetBSON ensures that each embedded node is properly unmarshaled into the correct concrete type.
The above is the detailed content of How to Unmarshal Embedded Nodes of Different Types Using Interfaces in mgo (Go)?. For more information, please follow other related articles on the PHP Chinese website!