Created
January 24, 2013 21:35
-
-
Save hnaohiro/4627996 to your computer and use it in GitHub Desktop.
Golangでreflectを使ってstructからmapへ変換
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(data interface{}) map[string]interface{} { | |
result := make(map[string]interface{}) | |
elem := reflect.ValueOf(data).Elem() | |
size := elem.NumField() | |
for i := 0; i < size; i++ { | |
field := elem.Type().Field(i).Name | |
value := elem.Field(i).Interface() | |
result[field] = value | |
} | |
return result | |
} | |
type Hoge struct { | |
Fuga int | |
Moge string | |
} | |
func main() { | |
hoge := Hoge{100, "hello"} | |
m := StructToMap(&hoge) | |
fmt.Println(m) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment