Thomas McGoey-Smith

Adding Multiple Struct Tags in Go

So this week I’ve had to decode some json and save it into my database.

One thing I wanted to do was just use a single struct. However I wasn’t sure how I could easily use Go’s struct tags.

For example:

I wanted to do something like this:

// Order struct for working with json
type Order struct {
    ID          int     `json:"id"`
    Email       string  `json:"email"`
    AddressLine string  `json:"address_line"`
    ...
}

// Order struct for working with a DB
type Order struct {
    ID          int     `db:"id"`
    Email       string  `db:"email"`
    AddressLine string  `db:"address"`
    ...
}

Luckily, I happened to come across this comment on Hacker News.

...
Spent a whole day trying to figure out why only the first tag in
the struct was 'active':

  Name string `xml:"name", db:"name"`  //<--- XML works, DB doesn't

  Name string `db:"name", xml:"name"`  //<--- DB works, XML doesn't


The answer was, going from memory, I added a comma (,) between the tags.
Should have been:

  Name string `xml:"name" db:"name"`
...

Now I can do something like this:

// Order struct for working with json and a DB
type Order struct {
    ID          int     `json:"id" db:"id"`
    Email       string  `json:"email" db:"email"`
    AddressLine string  `json:"address_line" db:"address"`
    ...
}

@tamcgoey on Jul 21, 2015

Enjoyed the article? Subscribe to my newsletter for more.

© Thomas McGoey-Smith (2014-2018). RSS.