Skip to content

Instantly share code, notes, and snippets.

@rming
Last active May 16, 2019 02:37
Show Gist options
  • Select an option

  • Save rming/0169634a402162e4573755abfde443a7 to your computer and use it in GitHub Desktop.

Select an option

Save rming/0169634a402162e4573755abfde443a7 to your computer and use it in GitHub Desktop.
StructToMap.go
package main
import (
"fmt"
"reflect"
)
func StructToMap(s interface{}) map[string]interface{} {
m := make(map[string]interface{})
elem := reflect.ValueOf(s).Elem()
tt := elem.Type()
for i := 0; i < tt.NumField(); i++ {
m[tt.Field(i).Name] = elem.Field(i).Interface()
}
return m
}
type People struct {
Name string
Age int
}
func main() {
p1 := &People{"xiaoming", 23}
fmt.Println(p1.Name, p1.Age)
xiaoming := StructToMap(p1)
fmt.Println(xiaoming)
}
// xiaoming 23
// map[Age:23 Name:xiaoming]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment