跳转至

Golang 速成 | 结构体标签

主要应用

  • JSON 编码/解码
  • ORM 映射关系

结构体标签示例

Go
package main

import (
    "fmt"
    "reflect"
)

type resume struct {
    Name string `json:"name" doc:"我的名字"`
}

func findDoc(stru interface{}) map[string]string {
    t := reflect.TypeOf(stru).Elem()
    doc := make(map[string]string)

    for i := 0; i < t.NumField(); i++ {
        doc[t.Field(i).Tag.Get("json")] = t.Field(i).Tag.Get("doc")
    }

    return doc

}

func main() {
    var stru resume
    doc := findDoc(&stru)
    fmt.Printf("name字段为:%s\n", doc["name"])
}

结构体标签在 JSON 中的应用

Go
package main  

import (  
    "encoding/json"  
    "fmt"
    )  

type Movie struct {  
    Title  string   `json:"title"`  
    Year   int      `json:"year"`  
    Price  int      `json:"rmb"`  
    Actors []string `json:"actors"`  
}  

func main() {  
    movie := Movie{"喜剧之王", 2000, 10, []string{"xingye", "zhangbozhi"}}  

    //编码的过程  结构体---> json  
    jsonStr, err := json.Marshal(movie)  
    if err != nil {  
       fmt.Println("json marshal error", err)  
       return  
    }  

    fmt.Printf("jsonStr = %s\n", jsonStr)  

    //解码的过程 jsonstr ---> 结构体  
    //jsonStr = {"title":"喜剧之王","year":2000,"rmb":10,"actors":["xingye","zhangbozhi"]}  
    myMovie := Movie{}  
    err = json.Unmarshal(jsonStr, &myMovie)  
    if err != nil {  
       fmt.Println("json unmarshal error ", err)  
       return  
    }  

    fmt.Printf("%v\n", myMovie)  
}