Go 비공개 필드를 포함하는 structToMap()

개요[ | ]

Go 비공개 필드를 포함하는 structToMap()
package main

import (
	"fmt"
	"reflect"
	"unsafe"
)

func structToMap(data interface{}) map[string]interface{} {
	v := reflect.ValueOf(data)
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}
	if v.Kind() != reflect.Struct {
		panic("structToMap only accepts structs")
	}
	t := v.Type()
	result := make(map[string]interface{})
	for i := 0; i < v.NumField(); i++ {
		field := t.Field(i)
		fieldValue := v.Field(i)
		if field.PkgPath != "" {
			fieldValue = reflect.NewAt(fieldValue.Type(), unsafe.Pointer(fieldValue.UnsafeAddr())).Elem()
		}
		result[field.Name] = fieldValue.Interface()
	}
	return result
}

type Example struct {
	Exported   string
	unexported string
}

func main() {
	e := Example{
		Exported:   "Hello",
		unexported: "World",
	}
	result := structToMap(&e)
	fmt.Println(result)
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}