在struct标记中使用变量 [英] Using a variable in the struct tag
问题描述
如何在Go struct标签中使用变量?
How would I use a variable in a Go struct tag?
这有效:
type Shape struct {
Type string `json:"type"`
}
这不起作用:
const (
TYPE = "type"
)
type Shape struct {
Type string fmt.Sprintf("json:\"%s\"", TYPE)
}
在第一个示例中,我使用有效的字符串文字.在第二个示例中,我正在使用fmt.Sprintf
构建字符串,并且似乎出现错误:
syntax error: unexpected name, expecting }
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 }
这里是围棋操场: https://play.golang.org/p/lUmylztaFg
推荐答案
如何在Go struct标签中使用变量?您不会,这是语言所不允许的.您不能使用在运行时求值的语句代替编译时字符串文字作为结构体字段的注释.据我所知,任何一种编译语言都无法正常工作.
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.
这篇关于在struct标记中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!