Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function for converting a struct to map in Golang

Tags:

go

I want to convert a struct to map in Golang. It would also be nice if I could use the JSON tags as keys in the created map (otherwise defaulting to field name).

Edit Dec 14, 2020

Since structs repo was archived, you can use mapstructure instead.

Edit TL;DR version, Jun 15, 2015

If you want the fast solution for converting a structure to map, see the accepted answer, upvote it and use that package.

Happy coding! :)


Original Post

So far I have this function, I am using the reflect package but I don't understand well how to use the package, please bear with me.

func ConvertToMap(model interface{}) bson.M {     ret := bson.M{}      modelReflect := reflect.ValueOf(model)      if modelReflect.Kind() == reflect.Ptr {         modelReflect = modelReflect.Elem()     }      modelRefType := modelReflect.Type()     fieldsCount := modelReflect.NumField()      var fieldData interface{}      for i := 0; i < fieldsCount; i++ {         field := modelReflect.Field(i)          switch field.Kind() {         case reflect.Struct:             fallthrough         case reflect.Ptr:             fieldData = ConvertToMap(field.Interface())         default:             fieldData = field.Interface()         }          ret[modelRefType.Field(i).Name] = fieldData     }      return ret } 

Also I looked at JSON package source code, because it should contain my needed implementation (or parts of it) but don't understand too much.

like image 250
eAbi Avatar asked May 11 '14 06:05

eAbi


People also ask

Is there a map function in Golang?

Map() Function in Golang is used to return a copy of the string given string with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the string with no replacement.

Can struct be key in map Golang?

In maps, most of the data types can be used as a key like int, string, float64, rune, etc. Maps also allow structs to be used as keys.

Is map a type in Golang?

What map types exist in Go? There's no specific data type in Golang called map ; instead, we use the map keyword to create a map with keys of a certain type, and values of another type (or the same type). In this example, we declare a map that has string s for its keys, and float64 s for its values.

Is struct value type in Golang?

Structs are value types. When you assign one struct variable to another, a new copy of the struct is created and assigned. Similarly, when you pass a struct to another function, the function gets its own copy of the struct .


1 Answers

I also had need for something like this. I was using an internal package which was converting a struct to a map. I decided to open source it with other struct based high level functions. Have a look:

https://github.com/fatih/structs

It has support for:

  • Convert struct to a map
  • Extract the fields of a struct to a []string
  • Extract the values of a struct to a []values
  • Check if a struct is initialized or not
  • Check if a passed interface is a struct or a pointer to struct

You can see some examples here: http://godoc.org/github.com/fatih/structs#pkg-examples For example converting a struct to a map is a simple:

type Server struct {     Name    string     ID      int32     Enabled bool }  s := &Server{     Name:    "gopher",     ID:      123456,     Enabled: true, }  // => {"Name":"gopher", "ID":123456, "Enabled":true} m := structs.Map(s) 

The structs package has support for anonymous (embedded) fields and nested structs. The package provides to filter certain fields via field tags.

like image 148
Fatih Arslan Avatar answered Oct 24 '22 15:10

Fatih Arslan