Struct Tags for Encoding/Decoding Data

· 190 words · 1 minute read

In Go, we use structs to define and group data, as we would use classes in other OOP languages. However, in Go the naming of attributes within the struct is important because if it starts with a lower-case it’s seen as private and with an upper-case first letter it’s seen as public.

We can encode these structs into data formats like json but we might want to rename the fields, struct tags allow us to do this. They are defined using back ticks after the type declaration.

1
2
3
4
5
type Address struct {
    Line1    string `json:"line_1"`
    City     string `json:"city"`
    Postcode string `json:"postcode"`
}

Multiple Tags: For when you need to use multiple tags they can be separated by spaces.

1
2
3
4
type Person struct {
    FirstName string `json:"first_name" bson:"first_name"`
    LastName  string `json:"last_name" bson:"last_name"`
}

Ignore Empty: When encoding to JSON, we might not want to print out data with hasn’t been defined. To do this we use the omitempty tag within the name of the item.

1
2
3
4
5
type Animal struct {
    Name  string `json:"name"`
    Noise string `json:"noise,omitempty"`
    Size  string `json:",omitempty"`
}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!