Home >Backend Development >Golang >How Can I Efficiently Convert a Go Struct to a Map?
Converting a struct to a map can be useful in various scenarios, such as marshalling data to JSON or interacting with dynamic systems. This question explores how to achieve this conversion in Go, utilizing both the standard library and third-party packages.
The question presents an original implementation using the reflect package:
func ConvertToMap(model interface{}) bson.M { // ... Implementation }
However, the original implementation relies heavily on reflection, which can impact performance and doesn't support features like custom field tags.
The accepted answer introduces the structs package, a convenient third-party solution that provides a robust and efficient conversion from a struct to a map:
import "github.com/fatih/structs" type Server struct { Name string ID int32 Enabled bool } // Convert to a map m := structs.Map(&Server{ Name: "gopher", ID: 123456, Enabled: true, })
The structs package offers several advantages over the original implementation:
The above is the detailed content of How Can I Efficiently Convert a Go Struct to a Map?. For more information, please follow other related articles on the PHP Chinese website!