To convert a struct to a map with field names as keys using reflection in Golang, you can use the following steps:
Here is an example implementation:
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
Email string
}
func convertStructToMap(data interface{}) map[string]interface{} {
result := make(map[string]interface{})
val := reflect.ValueOf(data)
typ := reflect.TypeOf(data)
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
value := val.Field(i).Interface()
result[field.Name] = value
}
return result
}
func main() {
person := Person{
Name: "John Doe",
Age: 30,
Email: "[email protected]",
}
fmt.Println(convertStructToMap(person))
}
This will output:
map[Name:John Doe Age:30 Email:[email protected]]
The convertStructToMap
function takes the struct as input and returns a map with the field names as keys and their corresponding values. The reflect
package is used to retrieve the type and value of the struct fields.