您好,登錄后才能下訂單哦!
本文章向大家介紹怎么在golang將Struct轉換成map,主要包括怎么在golang將Struct轉換成map的使用實例、應用技巧、基本知識點總結和需要注意事項,具有一定的參考價值,需要的朋友可以參考一下。
golang 是Google開發的一種靜態強類型、編譯型、并發型,并具有垃圾回收功能的編程語言,其語法與 C語言相近,但并不包括如枚舉、異常處理、繼承、泛型、斷言、虛函數等功能。
mport ( "encoding/json" "fmt" "reflect" "time" ) type Persion struct { Id int Name string Address string Email string School string City string Company string Age int Sex string Proviece string Com string PostTo string Buys string Hos 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
到此這篇關于怎么在golang將Struct轉換成map的文章就介紹到這了,更多相關的內容請搜索億速云以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持億速云!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。