Converting Maps to Structs in Go
Question:
How can we efficiently convert a map with string keys and interface{} values into a corresponding struct?
Answer:
There are two primary approaches:
Using mapstructure:
import "github.com/mitchellh/mapstructure" mapstructure.Decode(myData, &result)
Custom Implementation:
func SetField(obj interface{}, name string, value interface{}) error { // Logic for setting the field value } func (s *MyStruct) FillStruct(m map[string]interface{}) error { // Iterate over the map and set the struct fields } // Example usage func main() { result := &MyStruct{} err := result.FillStruct(myData) if err != nil { fmt.Println(err) } }
Note:
Both approaches assume that the struct field names match the map keys, and the values are of the correct type. Handling these cases requires additional code.
The above is the detailed content of How to Efficiently Convert Go Maps to Structs?. For more information, please follow other related articles on the PHP Chinese website!