Here is the step-by-step guide to converting struct fields to map in Go:
- Use the “reflect” package to inspect the struct’s fields.
- Iterate over the struct’s fields, retrieving the field name and value.
- Store each field name and value in a map.
Example
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
}
func StructToMapString(input interface{}) map[string]interface{} {
result := make(map[string]interface{})
// Use reflection to inspect the input
value := reflect.ValueOf(input)
typeOf := value.Type()
// Iterate over the fields of the struct
for i := 0; i < value.NumField(); i++ {
fieldName := typeOf.Field(i).Name
fieldValue := value.Field(i).Interface()
result[fieldName] = fieldValue
}
return result
}
func main() {
p := Person{Name: "John", Age: 30}
mapped := StructToMapString(p)
fmt.Println(mapped)
}
Output
map[Age:30 Name:John]
That’s it!
Conclusion
To convert a golang struct to a map, use the reflect package, iterate over the struct’s fields, and store each field name and value.
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.