Golang Struct tagged structure

In addition to the name and type, the fields in the structure can also have an optional tag (tag): it is a string attached to the field, which can be a document or other important tags.

The content of the tag cannot be used in general programming, only the package reflect can get it, it can introspect the type, attribute and method at runtime, for example: calling reflect.TypeOf() on a variable can get the correct type of the variable, If the variable is a structure type, you can use Field to index the fields of the structure, and then you can use the Tag property.

Example 10.7 struct_tag.go:

package main

import (
    "fmt"
    "reflect"
)

type TagType struct { // tags
    field1 bool   "An important answer"
    field2 string "The name of the thing"
    field3 int    "How much there are"
}

func main() {
    tt := TagType{true, "Barak Obama", 1}
    for i := 0; i < 3; i++ {
        refTag(tt, i)
    }
}

func refTag(tt TagType, ix int) {
    ttType := reflect.TypeOf(tt)
    ixField := ttType.Field(ix)
    fmt.Printf("%v\n", ixField.Tag)
}

output:

An important answer
The name of the thing
How much there are

Guess you like

Origin blog.csdn.net/qq_34556414/article/details/130053137