type People struct {
Name string `json:"name"`
Age int8 `json:"age"`
}
在学习过程中,看到类似上面的代码,一下子懵了个逼?。。。大概一查,这是 Golang 中的 Tags 语法,官方解释是这样的:
A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. The tags are made visible through a reflection interface but are otherwise ignored.
官方的解释不够接地气,像我这样的初学者看了等于是没看的,我们加点实际场景进去就能明白这到底能干吗。
由于 Golang 中对字段的标记可以在 反射 时获取到,所以通常是用来在将 struct 编码转换的过程中提供一些转换规则的信息,比如?下面例子中提到的 JSON 转换。当然你也可以用它来存储你想要的任何其他元信息(Meta-information)。
举例子
举一个 API 的例子 ?,获取用户ID为1的用户信息:GET /v1/user/1
。简单的做法是在获取到数据库 user 表的一条记录后,以 JSON 格式返回。
type User struct {
Id int
Name string
Age int8
}
如果不做任何处理,那么此时返回的数据应该是如下:
{
"Id":1,"Name":"X.FLY"