Dong.Ge

左手代码 右手江湖

golang map和struct互转

东哥's Avatar 2019-08-23

  1. map转struct
  2. struct转map

map转struct

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

借助第三方包 github.com/goinggo/mapstructure
type InviteReward struct {
MasterAccountId int64 `json:"m" mapstructure:"m"`
SlaveAccountId int64 `json:"s" mapstructure:"s"`
RewardId int64 `json:"r" mapstructure:"r"`
}
func MapToStruct(){
mapInstance := make(map[string]interface{})
mapInstance["m"] = 11
mapInstance["s"] = 18

var people People
err := mapstructure.Decode(mapInstance, &people)
if err != nil {
fmt.Println(err)
}
fmt.Println(people)
}

struct转map

1
2
3
4
5
6
7
8
9
10
11
func StructToMap(obj interface{}) map[string]interface{}{
obj1 := reflect.TypeOf(obj)
obj2 := reflect.ValueOf(obj)

var data = make(map[string]interface{})
for i := 0; i < obj1.NumField(); i++ {
data[obj1.Field(i).Name] = obj2.Field(i).Interface()
}
return data
}

本文最后更新于 天前,文中所描述的信息可能已发生改变