Combine Multiple Field Tags in Go

I work a lot with JSON APIs in my Go projects, so almost every struct has some field tags on it to translate AccountID into account_id and that sort of thing. Then one day I needed to load data from config using mapstructure and it took a few attempts with the search engine to find the syntax I needed, so it’s here for next time I need it (or in case you need it too).

Combining JSON and Mapstructure

An example truly is worth a thousand words! (This one is from the code that drives the neopixel shelf):

type LEDColour struct {
	Red   uint8 `mapstructure:"red" json:"red"`
	Green uint8 `mapstructure:"green" json:"green"`
	Blue  uint8 `mapstructure:"blue" json:"blue"`
	White uint8 `mapstructure:"white" json:"white"`

It turns out that the reason I couldn’t find examples of how to combine struct field tags is because you don’t! You just add each one required, followed by a space, and then the next, and so on. How simple, how elegant … how Go!

Also published on Medium.

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.