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!

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.

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Find out more about Webmentions.)