How to create a map from a struct's fields and values using reflection in Golang?

To create a map from a struct's fields and values using reflection in Golang, you can use the reflect package. Here's an example of how to achieve this:

package main import ( "fmt" "reflect" ) type Person struct { Name string Age int Country string } func main() { p := Person{ Name: "John", Age: 30, Country: "USA", } pMap := structToMap(p) fmt.Println(pMap) } func structToMap(obj interface{}) map[string]interface{} { objValue := reflect.ValueOf(obj) objType := objValue.Type() pMap := make(map[string]interface{}) for i := 0; i < objValue.NumField(); i++ { field := objValue.Field(i) fieldName := objType.Field(i).Name pMap[fieldName] = field.Interface() } return pMap }

In this example, the Person struct has three fields: Name, Age, and Country. The structToMap function takes an empty interface which can accept any type of struct. It uses reflection to iterate over the fields of the struct and creates a map with the field names as keys and their corresponding values as values.

The reflect.ValueOf(obj) function returns the reflect.Value representation of the struct object. NumField() returns the number of fields in the struct. Using a loop, we iterate over each field, get the field value using Field(i), and the field name using Field(i).Name. The field.Interface() function returns the value of the field as an interface{} type, which is then stored in the map with the field name as the key.

Finally, the pMap map containing the fields and values of the struct is returned.

When you run this code, it will output:

map[Name:John Age:30 Country:USA]

The resulting map has the field names and their respective values as key-value pairs.