SoFunction
Updated on 2025-05-23

Detailed explanation of the usage of Struct Tag in Go language

In Go, struct is a composite data type used to combine multiple different types of data into a single data unit. By using struct, complex data structures can be defined to facilitate organization and management of data. struct is a very important concept in the Go language, and it is widely used in data modeling, object representation, data transmission and other scenarios.

In Go language, Struct Tag is a mechanism used to add metadata to fields, which is often used in serialization (such as JSON, XML), ORM mapping, verification and other scenarios. When you develop web applications or process data interactions, you will often see writing methods like the following:

type User struct {
	Username string `json:"username"`
	Token    string `json:"token"`
}

Among themjson:"token"It is the field tag, which does not affect the syntax logic of the Go language itself, but it is very useful when using reflection, especially when you use standard libraries such as encoding/json.

1. Basic syntax of structure labels

The structure tag is a pair of backticks ` strings wrapped in, with a key-value pair:

FieldName FieldType `key:"value"`
//You can write multiple key-value pairs:FieldName FieldType `json:"token" xml:"token" validate:"required"`

These tags are parsed and used for other packages (usually libraries) and do not affect the behavior of the Go compiler.

2. The specific meaning of json:"token"

When you encode the structure into JSON using the encoding/json package, the function of this tag is:
Specify the serialized field name
By default, Go uses the structure field name as the field name of JSON. But note:
The fields of the Go structure begin with capital (export);
JSON is usually used in lowercase field names (such as "token");
In order to unify the backend return format and meet the front-end specification, we can explicitly specify the field name:

type User struct {
	Token string `json:"token"`
}

Generated json:

{
  "token": "abc123"
}

Deserialization also takes effect
When you deserialize JSON into a structure, Go finds the corresponding fields based on the label. For example, the above json format can be successfully mapped to:

var user User
(data, &user)
//  == "abc123"

3. Common label format variations

type User struct {
	Token string `json:"token"`           // explicitly specify the field name token	Age   int    `json:"-"`               // Ignore this field and do not serialize	Email string `json:"email,omitempty"` // If empty, ignore this field}

json: "-": means that this field will never be encoded or decoded, that is, it will not be exported.
json: "email,omitempty": means that only if the field is not the default value, it will be encoded to JSON (for example, if the string is "", the number is 0, it will be ignored).

IV. Use examples

package main
import (
	"encoding/json"
	"fmt"
)
type User struct {
	Username string `json:"username"`
	Token    string `json:"token"`
	Age      int    `json:"-"` // Not exported}
func main() {
	user := User{
		Username: "Alice",
		Token:    "abc123",
		Age:      30,
	}
	data, _ := (user)
	(string(data))
}
//{"username":"Alice","token":"abc123"}

5. Use suggestions

  • The field must be exported (capitalize) or the json package will not access it even with a tag.
  • It is recommended to use lowercase JSON field name: json: "username", which is more in line with the front-end JSON style.
  • If there are nested structures, please note that the substructures also add json tags. !!!~~~~~~~~~~~~!!! Be sure to add the json tag structure! ! ! ! Otherwise, the front-end cannot be parsed! ! !

doubt? If json tag is "-", why not lowercase the structure's first letter? Isn't it an effect?

json:"-"Uses
json: "-" is to explicitly tell encoding/json: "You don't need to deal with this field, ignore it when serializing/deserializing". This is useful when structs expose fields to the outside but do not want to be processed by JSON, for example:

type User struct {
	Username string `json:"username"`
	Password string `json:"-"` // Don't want to be output!}

You can still process the Password field in the backend, but it won't appear in the JSON output. This is a clear expression of security and structural clarity.
Summary: Select a suggestion

Purpose Recommended usage
Fields are only used for internal logic and do not want to be exposed Lowercase fields
Fields are visible to the program, but do not want to appear in JSON json:"-"
Need to appear in JSON but the field name is different json:"your_name"
Hope the field does not appear when empty json:"your_name,omitempty"

Simple example:

type RespMsg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}
type LoginData struct {
	Token    string `json:"token"`
	Username string `json:"username"`
	Location string `json:"location"`
}
rsp := RespMsg{
	Code: 200,
	Msg:  "success",
	Data: LoginData{
		Token:    userToken,
		Username: username,
		Location: "/static/view/",
	},
}

The JSON returned in this way is:

{
  "code": 200,
  "msg": "success",
  "data": {
    "token": "...",
    "username": "...",
    "location": "..."
  }
}

If you use the front-end , there will be no problem of case misalignment.

This is the end of this article about the detailed explanation of the usage of Struct Tag in Go. For more information about the usage of Go Struct Tag, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!