好湿?好紧?好多水好爽自慰,久久久噜久噜久久综合,成人做爰A片免费看黄冈,机机对机机30分钟无遮挡

主頁 > 知識庫 > Golang自定義結構體轉map的操作

Golang自定義結構體轉map的操作

熱門標簽:不封卡外呼系統 重慶慶云企業400電話到哪申請 地圖標注免費定制店 湛江crm外呼系統排名 寧波語音外呼系統公司 宿遷便宜外呼系統代理商 仙桃400電話辦理 鄭州智能語音電銷機器人價格 上海極信防封電銷卡價格

在Golang中,如何將一個結構體轉成map? 本文介紹兩種方法。第一種是是使用json包解析解碼編碼。第二種是使用反射,使用反射的效率比較高,代碼在這里。如果覺得代碼有用,可以給我的代碼倉庫一個star。

假設有下面的一個結構體

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 string, value interface{}) {
 return "time", p.Date.Format(timeLayout)
}

json包的marshal,unmarshal

先將結構體序列化成[]byte數組,再從[]byte數組序列化成結構體。

data, _ := json.Marshal(user)
m := make(map[string]interface{})
json.Unmarshal(data, m)

優勢

使用簡單 劣勢

效率比較慢

不能支持一些定制的鍵,也不能支持一些定制的方法,例如將struct的域展開等。

使用反射

本文實現了使用反射將結構體轉成map的方法。通過標簽(tag)和反射,將上文示例的newUser()返回的結果轉化成下面的一個map。

其中包含struct的域的展開,定制化struct的方法。

map[string]interface{}{
 "name":  "user",
 "no_dive": StructNoDive{NoDive: 1},
  // dive struct field
 "url":   "https://github.com/liangyaopei",
 "star":  1,
  // customized method
 "time":  "2020-07-21 12:00:00",
}

實現思路 源碼解析

1.標簽識別。

使用readTag方法讀取域(field)的標簽,如果沒有標簽,使用域的名字。然后讀取tag中的選項。目前支持3個選項

'-':忽略當前這個域

'omitempty' : 當這個域的值為空,忽略這個域

'dive' : 遞歸地遍歷這個結構體,將所有字段作為鍵

如果選中了一個選項,就講這個域對應的二進制位置為1.。

const (
 OptIgnore  = "-"
 OptOmitempty = "omitempty"
 OptDive   = "dive"
)
 
const (
 flagIgnore = 1  iota
 flagOmiEmpty
 flagDive
)
 
func readTag(f reflect.StructField, tag string) (string, int) {
 val, ok := f.Tag.Lookup(tag)
 fieldTag := ""
 flag := 0
 
 // no tag, use field name
 if !ok {
 return f.Name, flag
 }
 opts := strings.Split(val, ",")
 
 fieldTag = opts[0]
 for i := 1; i  len(opts); i++ {
 switch opts[i] {
 case OptIgnore:
  flag |= flagIgnore
 case OptOmitempty:
  flag |= flagOmiEmpty
 case OptDive:
  flag |= flagDive
 }
 }
 return fieldTag, flag
}

2.結構體的域(field)的遍歷。

遍歷結構體的每一個域(field),判斷field的類型(kind)。如果是string,int等的基本類型,直接取值,并且把標簽中的值作為key。

for i := 0; i  t.NumField(); i++ {
    ...
    switch fieldValue.Kind() {
 case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64:
  res[tagVal] = fieldValue.Int()
 case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64:
  res[tagVal] = fieldValue.Uint()
 case reflect.Float32, reflect.Float64:
  res[tagVal] = fieldValue.Float()
 case reflect.String:
  res[tagVal] = fieldValue.String()
 case reflect.Bool:
  res[tagVal] = fieldValue.Bool()
 default:
 }
  }
}

3.內嵌結構體的轉換

如果是結構體,先檢查有沒有實現傳入參數的方法,如果實現了,就調用這個方法。如果沒有實現,就遞歸地調用StructToMap方法,然后根據是否展開(dive),來把返回結果寫入res的map。

for i := 0; i  t.NumField(); i++ {
 fieldType := t.Field(i)
 
 // ignore unexported field
 if fieldType.PkgPath != "" {
  continue
 }
 // read tag
 tagVal, flag := readTag(fieldType, tag)
 
 if flagflagIgnore != 0 {
  continue
 }
 
 fieldValue := v.Field(i)
 if flagflagOmiEmpty != 0  fieldValue.IsZero() {
  continue
 }
 
 // ignore nil pointer in field
 if fieldValue.Kind() == reflect.Ptr  fieldValue.IsNil() {
  continue
 }
 if fieldValue.Kind() == reflect.Ptr {
  fieldValue = fieldValue.Elem()
 }
 
 // get kind
 switch fieldValue.Kind() {
 case reflect.Struct:
  _, ok := fieldValue.Type().MethodByName(methodName)
  if ok {
  key, value, err := callFunc(fieldValue, methodName)
  if err != nil {
   return nil, err
  }
  res[key] = value
  continue
  }
  // recursive
  deepRes, deepErr := StructToMap(fieldValue.Interface(), tag, methodName)
  if deepErr != nil {
  return nil, deepErr
  }
  if flagflagDive != 0 {
  for k, v := range deepRes {
   res[k] = v
  }
  } else {
  res[tagVal] = deepRes
  }
 default:
 }
  }
  ...
}
 
// call function
func callFunc(fv reflect.Value, methodName string) (string, interface{}, error) {
 methodRes := fv.MethodByName(methodName).Call([]reflect.Value{})
 if len(methodRes) != methodResNum {
 return "", nil, fmt.Errorf("wrong method %s, should have 2 output: (string,interface{})", methodName)
 }
 if methodRes[0].Kind() != reflect.String {
 return "", nil, fmt.Errorf("wrong method %s, first output should be string", methodName)
 }
 key := methodRes[0].String()
 return key, methodRes[1], nil
}

4.array,slice類型的轉換

如果是array,slice類型,類似地,檢查有沒有實現傳入參數的方法,如果實現了,就調用這個方法。如果沒有實現,將這個field的tag作為key,域的值作為value。

switch fieldValue.Kind() {
 case reflect.Slice, reflect.Array:
  _, ok := fieldValue.Type().MethodByName(methodName)
  if ok {
  key, value, err := callFunc(fieldValue, methodName)
  if err != nil {
   return nil, err
  }
  res[key] = value
  continue
  }
      res[tagVal] = fieldValue
      ....
}

5.其他類型

對于其他類型,例如內嵌的map,直接將其返回結果的值。

switch fieldValue.Kind() {
 ...
 case reflect.Map:
  res[tagVal] = fieldValue
 case reflect.Chan:
  res[tagVal] = fieldValue
 case reflect.Interface:
  res[tagVal] = fieldValue.Interface()
 default:
 }

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

您可能感興趣的文章:
  • golang 如何用反射reflect操作結構體
  • golang 實現兩個結構體復制字段
  • golang通過反射設置結構體變量的值
  • Golang空結構體struct{}用途,你知道嗎
  • golang修改結構體中的切片值方法
  • golang 結構體初始化時賦值格式介紹
  • 解決golang結構體tag編譯錯誤的問題

標簽:海南 青海 儋州 物業服務 西雙版納 電子產品 安康 遼寧

巨人網絡通訊聲明:本文標題《Golang自定義結構體轉map的操作》,本文關鍵詞  Golang,自定義,結構,體轉,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《Golang自定義結構體轉map的操作》相關的同類信息!
  • 本頁收集關于Golang自定義結構體轉map的操作的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 强3d女角色的二次元app| 日韩欧美福利| 国产白浆视频在线播放| 三级在线观看视频| 少妇做爰免费视频网站www| 国产亚洲AV日韩美AV资源吧| 青青草视频污版| 影音先锋AV啪啪资源| 多人性激烈的欧美三级视频 | 又黄又爽又色的性视频| 性巴西18videosex性高清| 欧美黄色片子| 夫妻啪啪自拍| 九月丁香激情综合婷婷玉立| 国产福利视频丝袜| 国产精品大屁股白浆免费A片 | 欧美日韩综合高清一区二区| 国精产品一区一区二区三区mba下载 | 欧美交片| 2022国产精品最新在线| 国产精品久草| 啊轻点h轻点| 精品视频国产| 白虎逼逼| 扒开腿cao烂你小sao货漫画| 久久91这里精品国产2020| 美女日批视频| 聊斋一级毛片又长又又粗又大| 国产羞羞视频在线观看| 国产农村一级毛卡片免费| 明星ai人脸替换脸网站免费| 欧美黄A片免费视频WWW| 涩涩屋app色版?网站破解版| 久久国产日韩精华液的功效 | 军人的粗大| 国模尺度私拍在线视频| 99re热视频这里只精品| 娇妻浪欲13部| 国产91人妻精品一区二区三| 欧美猛男巨茎自慰| 解开她胸罩使劲揉她奶视频|