Skip to content

Instantly share code, notes, and snippets.

@hnaohiro
Created January 24, 2013 21:35
Show Gist options
  • Save hnaohiro/4627996 to your computer and use it in GitHub Desktop.
Save hnaohiro/4627996 to your computer and use it in GitHub Desktop.
Golangでreflectを使ってstructからmapへ変換
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