This website recently got a major rebuild; if you're missing something, let Lorna know.

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!


In: tech
Tags: #go #tips