"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Unmarshal Embedded Nodes of Different Types Using Interfaces in mgo (Go)?

How to Unmarshal Embedded Nodes of Different Types Using Interfaces in mgo (Go)?

Published on 2024-11-10
Browse:191

 How to Unmarshal Embedded Nodes of Different Types Using Interfaces in mgo (Go)?

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3