Home > Backend Development > Golang > 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)?

Patricia Arquette
Release: 2024-10-29 06:10:30
Original
567 people have browsed it

 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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template