12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go言語でstructからmapへ変換

Posted at

構造体のフィールド一覧を取得したくなったので、reflectを使って実装。

struct2map.go
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)
}
12
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?