Hanlen
11/22/2019 - 10:05 AM

reflect test

// @copyright (C) ChinaNetCenter Inc. All rights reserved.
// @author linhr@wangsu.com
// @date 2019/08/23 17:00
// @description
package main

import (
	"fmt"
	"reflect"
	"strings"
)

type TestStruct struct {
	Id string `json:"name:id"`
	Flag int  `json:"name:flag"`
}

func refTest(a interface{}) {
	sType := reflect.TypeOf(a)
	sValue:= reflect.ValueOf(a)

	fmt.Printf("stype = %v, svalue = %v\n", sType, sValue)
	fmt.Printf("typeof sType kind = %v \n", sType.Kind())
	fmt.Printf("typeof sValue kind = %v \n", sValue.Kind())

	fmt.Printf("sValue elem = %v \n", sValue.Elem())
	fmt.Printf("sType elem = %v \n", sType.Elem())
	rm := make(map[string]interface{})
	rm["flag"] = 2
	rm["id"] = "ID007"

	if sValue.Kind() == reflect.Ptr {
		ssValue := sValue.Elem()
		for i := 0;i < ssValue.NumField(); i++ {
			fmt.Printf("field(%d) value = %v, kind = %v ", i, ssValue.Field(i), ssValue.Field(i).Kind())
			//fmt.Printf("field(%d)_tag = %v\n", i, sType.Elem().Field(i).Tag)

			s := string(sType.Elem().Field(i).Tag)
			fieldBegin := strings.IndexByte(s, '"')
			fieldEnd := strings.LastIndexByte(s, '"')
			items := strings.Split(s[fieldBegin+1:fieldEnd], ",")
			for _, v := range items {
				spIndex := strings.IndexByte(v, ':')
				t := v[:spIndex]
				vv := v[spIndex+1:]
				if t == "name" {
					fmt.Printf("tag_name = %s\n", vv)
					if dv, ok := rm[vv]; ok {
						switch ssValue.Field(i).Kind() {
						case reflect.Int:
							ssValue.Field(i).SetInt(int64(dv.(int)))
						case reflect.String:
							ssValue.Field(i).SetString(dv.(string))
						}
					}
				}
			}
		}
	}

	fmt.Println(a)
}

func main() {
	a := TestStruct{"ID001", 1}
	refTest(&a)

	return
}