Reputation: 9087
How would I use a variable in a Go struct tag?
This works:
type Shape struct {
Type string `json:"type"`
}
This does not work:
const (
TYPE = "type"
)
type Shape struct {
Type string fmt.Sprintf("json:\"%s\"", TYPE)
}
In the first example, I am using a string literal, which works. In the second example, I am building a string using fmt.Sprintf
, and I seem to be getting an error:
syntax error: unexpected name, expecting }
Here it is on the Go playground: https://play.golang.org/p/lUmylztaFg
Upvotes: 11
Views: 10957
Reputation: 465
String const/variable is not allowed in tag value to keep things simple and I support that. However with this limit, we need to use reflection to retrieve the tag value which is costly OR type string literals everywhere in the project, which may lead to bugs because of typos.
We can generate the tag values as string constant and then use this constant further in the project. It doesn't use reflection(saves performance cost), is more maintainable and removes the possibility of any bug because of typos.
ast
package is an amazing tool to analyse and generate the go code. For example -
type user struct {
Name string `json:"name"`
Age int `json:"age"`
}
We can generated constants for user
struct as below -
const (
UserNameJson = "name"
UserAgeJson = "age"
)
You may find tgcon helpful to generate the field tag value as const.
Upvotes: 1
Reputation: 111
With the introduction of go generate, it is possible to do achieve this.
However, go generate essentially makes the compilation a 2 phase process. Phase 1 generates the new code, phase 2 compiles and links etc.
There are a few limitations with using go generate:
go generate
every time it is needed and check in the result, since go generate
needs to be explicitly run before go build
Upvotes: 3
Reputation: 48076
How would I use a variable in a Go struct tag? You wouldn't, it's not allowed by the language. You can't use a statement that evaluates at runtime in place of a compile time string literal for as an annotation to a field on a struct. As far as I know nothing of the sort works in any compiled language.
Upvotes: 11