golang key map 所有_Golang反射:结构体(struct) 转化成map

本文介绍了两种将Golang结构体转化为map的方法:使用json包和反射。json包虽然简单但效率较低,不支持自定义键。反射方式则能处理结构体、内嵌结构体、array/slice以及其他类型,支持通过标签定制键。文章详细解析了反射实现的思路和源码,包括标签识别、域遍历、内嵌结构体和array/slice类型的转换。
摘要由CSDN通过智能技术生成

da72b2a8576b1af94d99c290f7c3f870.png

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

我的Github仓库​github.com

假设有下面的一个结构体

func 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 method
func (p Profile) StructToMap() (key stri
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值