如何在 Go 结构体标签中使用变量?
这有效:
type Shape struct {
Type string `json:"type"`
}
Run Code Online (Sandbox Code Playgroud)
这不起作用:
const (
TYPE = "type"
)
type Shape struct {
Type string fmt.Sprintf("json:\"%s\"", TYPE)
}
Run Code Online (Sandbox Code Playgroud)
在第一个示例中,我使用了一个字符串文字,它有效。在第二个示例中,我正在使用 构建一个字符串fmt.Sprintf
,但似乎出现错误:
syntax error: unexpected name, expecting }
这是在 Go 游乐场上:https : //play.golang.org/p/lUmylztaFg
如何在 Go 结构体标签中使用变量?你不会,这是语言所不允许的。您不能使用在运行时计算的语句代替编译时字符串文字作为结构上字段的注释。据我所知,在任何编译语言中都没有这种工作。
归档时间: |
|
查看次数: |
3917 次 |
最近记录: |