How to read struct field ` ` decorators?
go, json, struct, unmarshalling
Solution
First of all, what you call decorators are actually called tags. You can read these tags using reflection. The `reflect` package even has its own example for that.
Nevertheless, here's another example that prints all tags of the members of a struct (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)
}
}
Note that in case `f` is a pointer, e.g. a `*Foo`, you'd have to indirect (dereference) that value first or else the type returned by `TypeOf` is not a struct but a pointer and `NumField` as well as `Field()` would not work.
Problem
My package needs to be able to let my users define the fields backend database column name explicitly, if they want to. By default I will use the fields name - but sometimes they will need to manually specify the column name, just like the JSON package - unmarshal uses the explicit name if required. How can I consume this explicit value in my code? I don't even know what it's called so Google is really failing me at the moment. Here's what JSON's unmarshal function needs for example: ``` type User struct { Name string LastName string `json:"last_name"` CategoryId int `json:"category_id"` } ``` What would I need to use something like this? ``` // Paprika is my package name. type User struct { Name string LastName string `paprika:"last_name"` CategoryId int `paprika:"category_id"` } ``` My package will be constructing SQL queries and I can't just rely on the field's name - I need to be able to let them manually set the column name. So this is working with only the defined columns at the moment. ``` // 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 } ```