GoLang之结构体Tag讲解及规范

GoLang之结构体Tag讲解及规范,第1张

文章目录 GoLang之结构体Tag讲解及规范1.Tag介绍2.Tag规范2.1Tag统一规范2.2Tag不同库encoding/json规范举例 2.3Tag不同库gorm规范举例2.4go vet main.go命令

GoLang之结构体Tag讲解及规范 1.Tag介绍

Go语言提供了可通过反射发现的的结构体标签,这些在标准库json/xml中得到了广泛的使用;

orm框架也支持了结构体标签,上面那个例子的使用就是因为encoding/json支持了结构体标签,不过他有自己的标签规则(ORM全称是:Object Relational Mapping(对象关系映射));

jsonyamlgormvalidatemapstructureprotobuf这几个库的结构体标签是很常用的,gin框架就集成了validate库用来做参数校验;

Go官方已经帮忙整理了哪些库已经支持了struct tag,具体这些库中是怎么使用的,大家可以看官方文档https://github.com/golang/go/wiki/Well-known-struct-tags 介绍,写的都很详细,具体场景具体用:

TagDocumentation
xmlhttps://godoc.org/encoding/xml
jsonhttps://godoc.org/encoding/json
asn1https://godoc.org/encoding/asn1
reformhttps://godoc.org/gopkg.in/reform.v1
dynamodbhttps://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/dynamodbattribute/#Marshal
bigqueryhttps://godoc.org/cloud.google.com/go/bigquery
datastorehttps://godoc.org/cloud.google.com/go/datastore
spannerhttps://godoc.org/cloud.google.com/go/spanner
bsonhttps://godoc.org/labix.org/v2/mgo/bson, https://godoc.org/go.mongodb.org/mongo-driver/bson/bsoncodec
gormhttps://godoc.org/github.com/jinzhu/gorm
yamlhttps://godoc.org/gopkg.in/yaml.v2
tomlhttps://godoc.org/github.com/pelletier/go-toml
validatehttps://github.com/go-playground/validator
mapstructurehttps://godoc.org/github.com/mitchellh/mapstructure
parserhttps://godoc.org/github.com/alecthomas/participle
protobufhttps://github.com/golang/protobuf
dbhttps://github.com/jmoiron/sqlx
urlhttps://github.com/google/go-querystring
featurehttps://github.com/nikolaydubina/go-featureprocessing
2.Tag规范 2.1Tag统一规范

不同的库即使标签不一样,不过都有一个统一的总体规则:

(2)结构体标签可以有多个键值对

(2)键与值要用冒号分隔

(3)值要使用双引号括起来

(4)多个键值对之间要使用一个空格分隔,千万不要使用逗号!

`key1:"value1" key2:"value2" key3:"value3"...`  // 键值对用空格分隔
2.2Tag不同库encoding/json规范举例

如果我们想要在一个值中传递多个信息怎么办?不同库中实现的是不一样的,在encoding/json中,多值使用逗号分隔:

`json:"lon,omitempty"`
2.3Tag不同库gorm规范举例

如果我们想要在一个值中传递多个信息怎么办?不同库中实现的是不一样的,在gorm中,多值使用分号分隔:

`gorm:"column:id;primaryKey"
2.4go vet main.go命令

现在大家已经知道什么是结构体标签了,规则还是很规范的,但是很容易出错,因为Go语言在编译阶段并不会对其格式做合法键值对的检查,这样我们不小心写错了,就很难被发现,不过我们有go vet工具做检查,具体使用来看一个例子:

package main

type User struct {
	Name string `abc def ghk`
	Age  uint16 `123: 232`
}

func main() {
}


bad syntax for struct tag pair告诉我们键值对语法错误,bad syntax for struct tag value值语法错误;

所以在我们项目中引入go vet作为CI检查是很有必要的

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/995651.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存