
在Golang中,如何将一个结构体转成map? 本文介绍两种方法。第一种是是使用json
包解析解码编码。第二种是使用反射,使用反射的效率比较高,代码在
假设有下面的一个结构体
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