Search code examples
stringgostructgo-structtag

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


For some of my projects, I have had to use the viper package to use configuration. The package requires you to add the mapstructure:"fieldname" to identify and set your configuration object's fields correctly, but I have also had to add other tags for other purposes, leading to something looking like the following :

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

As you can see, it is quite redundant for me to write tag:"myField" for each of my tag, so I was wondering if there was any way to "bundle" them up and reduce the verbosity, with something like this mapstructure,json,yaml:"myField"

Or is it simply not possible and you must specify every tag separately ?


Solution

  • 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() to easily get tag values.

    The conventions do not support "merging" multiple tags, so just write them all out.

    The conventions, quoted from 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.

    See related question: What are the use(s) for tags in Go?