转到struct:在struct标记中使用变量

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

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.

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:

  1. Your library will not be 'go get'-able unless you run go generate every time it is needed and check in the result, since go generate needs to be explicitly run before go build
  2. This is a compile time process, so you will not be able to do it at run time using run time information. If you really must do this at run time, and in your case, you are just adding JSON serialization annotations, you could consider using a map.