Home > Article > Backend Development > How to set tag in golang
In the Go language, we can use structures to define a combined data type. Tag is a unique concept in the Go language. It allows us to attach meta-information to the fields of the structure. This meta-information can be obtained through reflection during runtime.
After the field defined by the structure, we can use a string enclosed by a set of symbols to represent the tag of this field. It can be a separate identifier or a list separated by spaces. . The syntax of Tag is as follows:
type StructName struct { FieldName FieldType `TagKey:"TagValue"` }
Here, FieldName
represents the declared field name, FieldType
represents the field type, and TagKey
and TagValue
represents the key and value of Tag respectively. If there are multiple key-value pairs, use spaces to separate them.
In the Go language, we can use reflection to obtain the structure and its fields, and we can use the reflect.StructTag
type method to obtain the Tag of a field. The example is as follows:
package main import ( "fmt" "reflect" ) type User struct { Name string `json:"name" log:"true"` Age int `json:"age" log:"false"` } func main() { user := User{ Name: "Alice", Age: 18, } t := reflect.TypeOf(user) for i := 0; i < t.NumField(); i++ { field := t.Field(i) fmt.Printf("%s: %s\n", field.Name, string(field.Tag)) fmt.Printf("json: %s\n", field.Tag.Get("json")) fmt.Printf("log: %s\n", field.Tag.Get("log")) } }
In the above example, we created a structure named User and defined two fields Name and Age in it, and then we used reflection to obtain the information of the structure, And output the Tag of each field. When outputting Tag, we use the Tag.Get()
method to obtain the value of the specified Tag key. The output result is as follows:
Name: json:"name" log:"true" json: name log: true Age: json:"age" log:"false" json: age log: false
You can see that when outputting the Tag information of the field, we use the string()
method to convert the reflect.StructTag
type of information as a string for more convenient output.
In addition to using Tags to add meta-information to the fields of the structure, we can also use Tags on the types we define to facilitate some processing of these types. A common way to use it is to use the Tag in the encoding
package on a custom type to specify some options during serialization, such as defining a date type:
type Date struct { Year int `json:"year"` Month int `json:"month"` Day int `json:"day"` }
Here, we are ## The three fields #Year,
Month, and
Day respectively use the
json key, and specify their names when serialized into JSON format data. In this way, when we serialize Date type data into JSON format, the JSON library will process the data in the way we specify.
The above is the detailed content of How to set tag in golang. For more information, please follow other related articles on the PHP Chinese website!