最近做Go開發的時候接觸到了一個新的orm第三方框架gorose,在使用的過程中,發現沒有類似beego進行直接對struct結構進行操作的方法,有部分API是通過map進行數據庫相關操作,那么就需要我們把struct轉化成map,下面是是我嘗試兩種不同struct轉換成map的方法
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
結論
通過比較可以看出,通過反射的形式轉換基本上是通過json形式轉換的兩倍。