你能用相同的值设置多个(不同的)标签吗?

Can you set multiple (different) tags with the same value?

对于我的一些项目,我不得不使用 viper 包来使用配置。 该包要求您添加 mapstructure:"fieldname" 以正确识别和设置配置对象的字段,但我还必须添加其他标签用于其他目的,导致如下所示:

type MyStruct struct {
    MyField string `mapstructure:"myField" json:"myField" yaml:"myField"`
}

如你所见,我为每个标签写 tag:"myField" 是多余的,所以我想知道是否有任何方法可以 "bundle" 它们并减少冗长, 像这样 mapstructure,json,yaml:"myField"

或者根本不可能,您必须分别指定每个标签?

Struct tags are arbitrary string literals. Data stored in struct tags may look like whatever you want them to be, but if you don't follow the conventions, you'll have to write your own parser / processing logic. If you follow the conventions, you may use StructTag.Get() and StructTag.Lookup() 轻松获取标签值。

约定不支持"merging"多个标签,全部写出来即可。

约定,引自reflect.StructTag

By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

参见相关问题:What are the use(s) for tags in Go?