使用Golang怎么将结构体装换为地图

  介绍

今天就跟大家聊聊有关使用Golang怎么将结构体装换为地图,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

假设有下面的一个结构体

func 分类列出(),User  {   ,name :=,“user"   ,MyGithub :=, GithubPage {   ,URL:“https://github.com/liangyaopei"   ,明星:1,   ,}   ,NoDive :=, StructNoDive {NoDive: 1}   ,dateStr :=,“2020 - 07 - 21, 12:00:00"   ,日期,_ :=, time.Parse (timeLayout, dateStr)   ,profile :=,概要文件{   ,经验:“my  experience"   ,日期:,,,,   ,}   ,return 用户{   名称:大敌;,,名字,   MyGithub, Github:大敌;   NoDive, NoDive:大敌;   ,MyProfile:概要文件,   ,}   }   ,   type  User  struct  {   ,Name , string ,,,的地图:“名字,omitempty",,,,//字符串   ,Github  GithubPage ,“地图:“github,潜水,omitempty" ',//struct 潜水   ,NoDive  StructNoDive “地图:“no_dive omitempty"”,,,//no  dive 结构   ,MyProfile  Profile ,,“地图:“my_profile omitempty"”,//, struct  implements  its  own 方法   }   ,   type  GithubPage  struct  {   ,URL  string “地图:“url"”   ,Star  int “地图:“star"”   }   ,   type  StructNoDive  struct  {   NoDive  int   }   ,   type  Profile  struct  {   ,Experience  string “地图:“experience"”   ,Date ,, time.Time “地图:“time"”   }   ,//,its  own  toMap 方法   func  (p 配置文件),StructToMap(),(字符串,key  value 界面{}),{   ,return “time",, p.Date.Format (timeLayout)   }

json包的元帅,解组

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

数据,_ :=, json.Marshal(和用户)   m :=,使接口(map [string] {})   json.Unmarshal(数据,,,米)

优势

使用简单劣势

效率比较慢

不能支持一些定制的键,也不能支持一些定制的方法,例如将结构的域展开等。

使用反射

本文实现了使用反射将结构体转成图的方法。通过标签(标记)和反射,将上文示例的分类列出()返回的结果转化成下面的一个地图。

其中包含结构的域的展开,定制化结构的方法。

map [string]接口{}{   ,“name":,“user",   ,“no_dive": StructNoDive {NoDive: 1},//才能,dive  struct 字段   ,“url":,,,, https://github.com/liangyaopei"   ,“star":,, 1,//才能,customized 方法   ,“time":,“2020 - 07 - 21, 12:00:00",   }

实现思路,源码解析

<强> 1。标签识别。

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

& # 39; & # 39;:忽略当前这个域

& # 39; omitempty& # 39;:当这个域的值为空,忽略这个域

& # 39;潜水# 39;:递归地遍历这个结构体,将所有字段作为键

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

const  (   ,OptIgnore =,“产生绯闻;=,OptOmitempty “omitempty"   ,OptDive ,,=,“dive"   )   ,   const  (   ,flagIgnore =, 1, & lt; & lt;极微小   ,flagOmiEmpty   ,flagDive   )   ,   func  readTag (f  reflect.StructField, tag 字符串),(字符串,int), {   ,val, ok :=, f.Tag.Lookup(标签)   ,fieldTag :=,““   ,flag :=0   ,   ,//no 标签,use  field 名称   ,if  ! ok , {   ,return  f.Name国旗   ,}   ,opts :=, strings.Split (val,,,,,)   ,=,fieldTag 选择[0]   ,for 小姐::=,1;,小姐:& lt;, len(选择);,我+ +,{   ,switch 选择[我],{   ,case  OptIgnore:   flag 才能|=flagIgnore   ,case  OptOmitempty:   flag 才能|=flagOmiEmpty   ,case  OptDive:   flag 才能|=flagDive   ,}   ,}   ,return  fieldTag国旗   }

<强> 2。结构体的域(领域)的遍历。

遍历结构体的每一个域(字段),判断字段的类型(类)。如果是字符串,整数等的基本类型,直接取的值,并且把标签中的值作为关键。

使用Golang怎么将结构体装换为地图