title: function for converting a struct to map in Golang
body: <p>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).</p>
  <h3>Edit Dec 14, 2020</h3>
  <p>Since <a href="https://github.com/fatih/structs" rel="noreferrer">structs</a> repo was archived, you can use <a href="https://github.com/mitchellh/mapstructure" rel="noreferrer">mapstructure</a> instead.</p>
  <h3>Edit TL;DR version, Jun 15, 2015</h3>
  <p>If you want the fast solution for converting a structure to map, see the <a href="https://stackoverflow.com/questions/23589564/function-for-converting-a-struct-to-map-in-golang#25117810">accepted answer</a>, upvote it and use that package.</p>
  <p>Happy coding! :)</p>
  <hr />
  <h3>Original Post</h3>
  <p>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.</p>
  <pre><code>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 &lt; 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
  }
  </code></pre>
  <p>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.</p>