1
0

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 3 years have passed since last update.

Go: struct を map に変換

Posted at

Go の struct を map に変換する方法です。

struct_to_map.go
// ----------------------------------------------------------------
//
//	struct_to_map.go
//
//				  Jan/31/2021
//
// ----------------------------------------------------------------
package main

import (
	"fmt"
	"reflect"
)

type City struct {
	Id	string
	Name_city	string
	Population	int
	Date_mod	string
}

// ---------------------------------------------------------------
func main() {
	fmt.Println ("*** 開始 ***")

	aa := City{Id: "t0921", Name_city: "宇都宮", Population: 34126, Date_mod: "2018-3-2"}

	fmt.Println (aa)

	unit_aa := make (map[string]interface{})

	tt := reflect.TypeOf(aa)
	vv := reflect.ValueOf(aa)

	for it:=0; it < tt.NumField(); it++ {
		ff := tt.Field(it)
		key := ff.Name
		value := vv.FieldByName(key).Interface()

		fmt.Println(key, value)

		unit_aa[key] = value
		}
	
	fmt.Println (unit_aa)

	fmt.Println ("*** 終了 ***")
}

// ----------------------------------------------------------------

実行結果

$ go run struct_to_map.go
*** 開始 ***
{t0921 宇都宮 34126 2018-3-2}
Id t0921
Name_city 宇都宮
Population 34126
Date_mod 2018-3-2
map[Date_mod:2018-3-2 Id:t0921 Name_city:宇都宮 Population:34126]
*** 終了 ***
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?