Golang反射:结构体(struct) 转化成map

您所在的位置:网站首页 golang反射获取struct坐成SQL Golang反射:结构体(struct) 转化成map

Golang反射:结构体(struct) 转化成map

2024-03-01 11:32| 来源: 网络整理| 查看: 265

在Golang中,如何将一个结构体转成map?本文介绍两种方法。第一种是是使用json包解析解码编码。第二种是使用反射,使用反射的效率比较高,代码在这里。

假设有下面的一个结构体

12345678910111213141516171819202122232425262728293031323334353637383940414243444546func newUser() User { name := "user" MyGithub := GithubPage{ URL: "https://github.com/liangyaopei", Star: 1, } NoDive := StructNoDive{NoDive: 1} dateStr := "2020-07-21 12:00:00" date, _ := time.Parse(timeLayout, dateStr) profile := Profile{ Experience: "my experience", Date: date, } return User{ Name: name, Github: MyGithub, NoDive: NoDive, MyProfile: profile, }}type User struct { Name string `map:"name,omitempty"` // string Github GithubPage `map:"github,dive,omitempty"` // struct dive NoDive StructNoDive `map:"no_dive,omitempty"` // no dive struct MyProfile Profile `map:"my_profile,omitempty"` // struct implements its own method}type GithubPage struct { URL string `map:"url"` Star int `map:"star"`}type StructNoDive struct { NoDive int}type Profile struct { Experience string `map:"experience"` Date time.Time `map:"time"`}// its own toMap methodfunc (p Profile) StructToMap() (key string, value interface{}) { return "time", p.Date.Format(timeLayout)} json包的marshal,unmarshal

先将结构体序列化成[]byte数组,再从[]byte数组序列化成结构体。

123data, _ := json.Marshal(&user)m := make(map[string]interface{})json.Unmarshal(data, &m)

优势

使用简单劣势 效率比较慢 不能支持一些定制的键,也不能支持一些定制的方法,例如将struct的域展开等。 使用反射

本文实现了使用反射将结构体转成map的方法。通过标签(tag)和反射,将上文示例的newUser()返回的结果转化成下面的一个map。其中包含struct的域的展开,定制化struct的方法。

123456789map[string]interface{}{ "name": "user", "no_dive": StructNoDive{NoDive: 1}, // dive struct field "url": "https://github.com/liangyaopei", "star": 1, // customized method "time": "2020-07-21 12:00:00",} 实现思路 & 源码解析1.标签识别。

使用readTag方法读取域(field)的标签,如果没有标签,使用域的名字。然后读取tag中的选项。目前支持3个选项

‘-‘:忽略当前这个域 ‘omitempty’ : 当这个域的值为空,忽略这个域 ‘dive’ : 递归地遍历这个结构体,将所有字段作为键

如果选中了一个选项,就讲这个域对应的二进制位置为1.。

123456789101112131415161718192021222324252627282930313233343536const ( OptIgnore = "-" OptOmitempty = "omitempty" OptDive = "dive")const ( flagIgnore = 1


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3