Last active
May 16, 2019 02:37
-
-
Save rming/0169634a402162e4573755abfde443a7 to your computer and use it in GitHub Desktop.
StructToMap.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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