Combine Multiple Field Tags in Go

Lorna Mitchell
1 min readOct 18, 2020

--

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](https://lornajane.net/posts/2020/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!

Originally published at LornaJane.

--

--

Lorna Mitchell

Polyglot programmer, technology addict, open source fanatic and incurable blogger (see http://lornajane.net)