Golang Struct to Map Conversion: A Comprehensive Guide with Example
To convert a Go struct to a map, you can use the reflect package. Here's an example:
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
Country string
}
func main() {
p := Person{Name: "John", Age: 30, Country: "USA"}
m := structToMap(p)
fmt.Println(m) // Output: map[Name:John Age:30 Country:USA]
}
func structToMap(obj interface{}) map[string]interface{} {
objValue := reflect.ValueOf(obj)
objType := objValue.Type()
result := make(map[string]interface{})
for i := 0; i < objValue.NumField(); i++ {
field := objValue.Field(i)
fieldName := objType.Field(i).Name
result[fieldName] = field.Interface()
}
return result
}
In this example, we define a Person struct with three fields (Name, Age, and Country). We then create an instance of the struct and pass it to the structToMap function. This function uses reflection to iterate over the struct's fields, retrieves their values, and adds them to a map with the field names as keys. Finally, the resulting map is printed to the console.
原文地址: https://www.cveoy.top/t/topic/mLky 著作权归作者所有。请勿转载和采集!