2023年7月12日 星期三

紀錄一下 Go 的 struct field tag 的處理

struct field tag 指的是如下 struct 中的 `json:"id"` 這段字串

struct {
	Id uint `json:"id"`
}

最常使用到的情況就是 Standard library 的 xmljson library 了吧。

多組 tag

如果 field 有多組 tag,例如 json 一種 tag、xml 另一種,要以空格( ,unicode U+0020)分隔,如下

struct {
	Id uint `json:"id" xml:"data-id"`
}

讀取 tag

如果要讀取 tag,就要使用到 reflect library,見以下 code

package main

import (
	"fmt"
	"reflect"
)

type Data struct {
	Id   uint64 `json:"id" xml:"id,attr"`
	Name string `json:"name" xml:"name,attr" toml:"n"`
}

func main() {
	u := Data{}
	ut := reflect.TypeOf(u)
	for i := 0; i < ut.NumField(); i++ {
		fmt.Println("Field:", ut.Field(i).Name)

		fmt.Println("\tjson:", ut.Field(i).Tag.Get("json"))
		fmt.Println("\txml: ", ut.Field(i).Tag.Get("xml"))
		fmt.Println("\ttoml:", ut.Field(i).Tag.Get("toml"))
	}

}

上面的 code 會輸出

Field: Id
	json: id
	xml:  id,attr
	toml: 
Field: Name
	json: name
	xml:  name,attr
	toml: n

因為 Id 沒有 toml tag,所以會是空字串

參考資料

frank, (2021, July 11). Golang 语言 Struct 中字段的 Tag 怎么使用?. 微信公眾號: Golang语言开发栈. https://mp.weixin.qq.com/s?__biz=MzA4Mjc1NTMyOQ==&mid=2247484997&idx=1&sn=c37ee65e916a1fab1684ddbf04e93929&chksm=9f81ac2ba8f6253def64b6a0d234e5ff10a7d417c67f087fb9ab5f0cd498b6efa5a50cf82f5e&cur_album_id=1500326813942726656&scene=189#wechat_redirect

沒有留言:

張貼留言