我的包需要能够让我的用户明确定义字段后端数据库列名,如果他们愿意的话。
默认情况下,我将使用字段名称 - 但有时他们需要手动指定列名称,就像 JSON 包一样 - 如果需要,unmarshal 使用显式名称。
如何在我的代码中使用这个显式值?我什至不知道它叫什么,所以谷歌现在真的让我失望了。
以下是 JSON 的解码函数需要的示例:
type User struct {
Name string
LastName string `json:"last_name"`
CategoryId int `json:"category_id"`
}
我需要什么才能使用这样的东西?
// Paprika is my package name.
type User struct {
Name string
LastName string `paprika:"last_name"`
CategoryId int `paprika:"category_id"`
}
我的包将构建 SQL 查询,我不能只依赖字段的名称 - 我需要能够让他们手动设置列名称。所以目前这仅适用于定义的列。
// Extracts resource information using reflection and
// saves field names and types.
func loadTypeToSchema(resource interface{}) {
resourceType := reflect.TypeOf(resource)
// Grab the resource struct Name.
fullName := resourceType.String()
name := fullName[strings.Index(fullName, ".")+1:]
// Grabs the resource struct fields and types.
fieldCount := resourceType.NumField()
fields := make(map[string]string)
for i := 0; i <= fieldCount-1; i++ {
field := resourceType.Field(i)
fields[field.Name] = field.Type.Name()
}
// Add resource information to schema map.
schema[name] = fields
}
最佳答案
首先,你所说的装饰器其实叫tags .您可以使用反射读取这些标签。 reflect
包甚至有它的 own example为此。
不过,这是另一个打印结构成员的所有标签 ( Click to play ) 的示例:
type Foo struct {
A int `tag for A`
B int `tag for B`
C int
}
func main() {
f := Foo{}
t := reflect.TypeOf(f)
for i := 0; i < t.NumField(); i++ {
fmt.Println(t.Field(i).Tag)
}
}
请注意,如果 f
是一个指针,例如*Foo
,您必须首先间接(取消引用)该值,否则 TypeOf
返回的类型不是结构而是指针和 NumField
以及 Field()
将不起作用。
关于json - 如何读取结构字段 ` ` 装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23840362/