This article has participated in the Denver Nuggets Creators Camp 3 “More Productive writing” track, see details: Digg project | creators Camp 3 ongoing, “write” personal impact.
Go doesn’t have a concept like a class, but you can do object-oriented programming with structs. Some of the basic uses of struct structures can be seen in the previous article – the use of structures and interfaces, portals.
This article focuses on the tags that can be attached to structs when they are declared. Tags are used to mark fields, mainly in reflection scenarios, and the Reflect package provides methods for manipulating tags.
The essence of the Tag
Rules of the Tag
The Tag itself is a string, which is a key:value pair separated by Spaces
- Key: the string must be non-empty and cannot contain control characters, Spaces, quotation marks, or colons
- Value: string marked with double quotation marks
- Note: No Spaces before or after the colon
type Person struct {
Name string `key1:"value1" key2:"value2"` / / name
Age uint `key3:"value3"`/ / age
}
Copy the code
A Tag is part of a Struct
How does Go manage struct fields? The following is the type declaration in the Reflect package, with some irrelevant code omitted:
// A StructField describes a single field in a struct.
type StructField struct {
// Name is the field name.
Name string. Type Type// field type
Tag StructTag // field tag string. }type StructTag string
Copy the code
As you can see, a struct member’s structure contains a StructTag, which is itself a string. So the Tag is actually part of the structure field.
Get the Tag
StructTag provides the Get(key String) string method to Get the Tag. Example:
package main
import (
"reflect"
"fmt"
)
type Person struct {
Name string `key1:"value1" key2:"value2"`
Age uint `key3:"value3"`
}
func main(a) {
s := Person{}
st := reflect.TypeOf(s)
fieldA := st.Field(0)
fmt.Printf("key1:%v\n", fieldA.Tag.Get("key1"))
fmt.Printf("key2:%v\n", fieldA.Tag.Get("key2"))
fieldB := st.Field(1)
fmt.Printf("key3:%v\n", fieldB.Tag.Get("key3"))}Copy the code
Running results:
key1:value1
key2:value2
key3:value3
Copy the code
Meaning of Tag
Use reflection to assign values to structure members dynamically, and use Tag to determine the action of the assignment. For example, the official Encoding/JSON package uses tags to Unmarshal json data into a structure. Based on the tag feature of struct, there are json, ORM and other applications. Using tag, it is common to deal with JSON data parsing and ORM mapping.