Go开发Struct转换成map两种方式比较
生活随笔
收集整理的這篇文章主要介紹了
Go开发Struct转换成map两种方式比较
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近做Go開發的時候接觸到了一個新的orm第三方框架gorose,在使用的過程中,發現沒有類似beego進行直接對struct結構進行操作的方法,有部分API是通過map進行數據庫相關操作,那么就需要我們把struct轉化成map,下面是是我嘗試兩種不同struct轉換成map的方法
mport ("encoding/json""fmt""reflect""time" )type Persion struct {Id intName stringAddress stringEmail stringSchool stringCity stringCompany stringAge intSex stringProviece stringCom stringPostTo stringBuys stringHos string }func main() {StructToMapViaJson()//StructToMapViaReflect() }func StructToMapViaJson() {m := make(map[string]interface{})t := time.Now()person := Persion{Id: 98439,Name: "zhaondifnei",Address: "大沙地",Email: "dashdisnin@126.com",School: "廣州第十五中學",City: "zhongguoguanzhou",Company: "sndifneinsifnienisn",Age: 23,Sex: "F",Proviece: "jianxi",Com: "廣州蘭博基尼",PostTo: "藍鯨XXXXXXXX",Buys: "shensinfienisnfieni",Hos: "zhonsndifneisnidnfie",}j, _ := json.Marshal(person)json.Unmarshal(j, &m)fmt.Println(m)fmt.Println(time.Now().Sub(t)) }一、通過struct轉json,json轉成map
func StructToMapViaJson() {m := make(map[string]interface{})t := time.Now()person := Persion{Id: 98439,Name: "zhaondifnei",Address: "大沙地",Email: "dashdisnin@126.com",School: "廣州第十五中學",City: "zhongguoguanzhou",Company: "sndifneinsifnienisn",Age: 23,Sex: "F",Proviece: "jianxi",Com: "廣州蘭博基尼",PostTo: "藍鯨XXXXXXXX",Buys: "shensinfienisnfieni",Hos: "zhonsndifneisnidnfie",}j, _ := json.Marshal(person)json.Unmarshal(j, &m)fmt.Println(m)fmt.Printf("duration:%d", time.Now().Sub(t)) } output: map[Proviece:jianxi Com:廣州蘭博基尼 Hos:zhonsndifneisnidnfie Name:zhaondifnei Company:sndifneinsifnienisn Buys:shensinfienisnfieni Age:23 PostTo:藍鯨XXXXXXXX Address:大沙地 School:廣州第十五中學 City:zhongguoguanzhou Sex:F Id:98439 Email:dashdisnin@126.com] duration:250467
二、通過反射形式生成map
func StructToMapViaReflect() {m := make(map[string]interface{})t := time.Now()person := Persion{Id: 98439,Name: "zhaondifnei",Address: "大沙地",Email: "dashdisnin@126.com",School: "廣州第十五中學",City: "zhongguoguanzhou",Company: "sndifneinsifnienisn",Age: 23,Sex: "F",Proviece: "jianxi",Com: "廣州蘭博基尼",PostTo: "藍鯨XXXXXXXX",Buys: "shensinfienisnfieni",Hos: "zhonsndifneisnidnfie",}elem := reflect.ValueOf(&person).Elem()relType := elem.Type()for i := 0; i < relType.NumField(); i++ {m[relType.Field(i).Name] = elem.Field(i).Interface()}fmt.Println(m)fmt.Printf("duration:%d", time.Now().Sub(t)) } output: map[Buys:shensinfienisnfieni Name:zhaondifnei City:zhongguoguanzhou Sex:F Proviece:jianxi Com:廣州蘭博基尼 Id:98439 School:廣州第十五中學 Address:大沙地 Age:23 PostTo:藍鯨XXXXXXXX Hos:zhonsndifneisnidnfie Email:dashdisnin@126.com Company:sndifneinsifnienisn] duration:104239結論
通過比較可以看出,通過反射的形式轉換基本上是通過json形式轉換的兩倍。
轉載于:https://www.cnblogs.com/dfsxh/p/10315442.html
總結
以上是生活随笔為你收集整理的Go开发Struct转换成map两种方式比较的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ubuntu安装Samba文件共享服务器
- 下一篇: py文件的运行