How to Convert Struct Fields into Map String

Here is the step-by-step guide to converting struct fields to map in Go:

  1. Use the “reflect” package to inspect the struct’s fields.
  2. Iterate over the struct’s fields, retrieving the field name and value.
  3. 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

Go map to struct

Go interface to struct

Go json to struct

Go struct to json