日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

golang 开发 Struct 转换成 map 两种方式比较

發布時間:2024/9/15 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 golang 开发 Struct 转换成 map 两种方式比较 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

原文鏈接:https://www.jianshu.com/p/81c4304f6d1b

最近做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)) }

二、通過反射形式生成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)) }

?

轉載于:https://www.cnblogs.com/wangjq19920210/p/11600479.html

總結

以上是生活随笔為你收集整理的golang 开发 Struct 转换成 map 两种方式比较的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。