What are the use(s) for struct tags in Go?

ghz 9months ago ⋅ 118 views

In the Go Language Specification, it mentions a brief overview of tags:

A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. The tags are made visible through a reflection interface but are otherwise ignored.

// A struct corresponding to the TimeStamp protocol buffer.
// The tag strings define the protocol buffer field numbers.
struct {
  microsec  uint64 "field 1"
  serverIP6 uint64 "field 2"
  process   string "field 3"
}

This is a very short explanation IMO, and I was wondering if anyone could provide me with what use these tags would be?

Answers

In Go, struct tags are commonly used in conjunction with reflection to provide metadata about struct fields. These tags are typically used by external packages to understand how to encode or decode structs, such as when marshaling or unmarshaling JSON or other formats.

Here are some common use cases for struct tags in Go:

  1. JSON Serialization/Deserialization: The encoding/json package uses struct tags to control the marshaling and unmarshaling of JSON data. For example, you can specify JSON field names, omitempty options, or custom encoding/decoding logic using struct tags.

    type Person struct {
        Name string `json:"name"`
        Age  int    `json:"age,omitempty"`
    }
    
  2. Database ORM: Object-Relational Mapping (ORM) libraries like GORM or sqlx use struct tags to map Go struct fields to database columns. You can specify column names, primary keys, or other database-specific settings using struct tags.

    type User struct {
        ID       uint   `gorm:"primaryKey"`
        Name     string `gorm:"column:name"`
        Password string `gorm:"column:password"`
    }
    
  3. Validation: Validation libraries like go-playground/validator use struct tags to define validation rules for struct fields. You can specify constraints such as required fields, string length limits, or custom validation functions using struct tags.

    type User struct {
        Username string `validate:"required,min=5,max=20"`
        Email    string `validate:"required,email"`
    }
    
  4. Documentation: Struct tags can also be used for documentation purposes. You can include additional information about struct fields that may be useful for developers or for generating documentation automatically.

    type Person struct {
        Name string `json:"name" doc:"The name of the person"`
        Age  int    `json:"age,omitempty" doc:"The age of the person"`
    }
    

Overall, struct tags provide a flexible mechanism for annotating struct fields with metadata, enabling seamless integration with external systems and providing additional context for developers.