How tags add meta-information to the structure and how to use it
Tags are a way of attaching additional information to structure fields.
Go specifications inStructure type definitionDefine the label as
The field declaration can be followed by an optional string literal label, which becomes the attribute of all fields in the corresponding field declaration. An empty label string is equivalent to a missing label. These marks are visible through the reflection interface and participate in the type identification of the structure, but will be ignored in other cases.
And provide an example:
struct {
x, y float64 "" // an empty tag string is like an absent tag
name string "any string is permitted as a tag"
_ [4]byte "ceci n'est pas un champ de structure"
}
// A struct corresponding to a TimeStamp protocol buffer.
// The tag strings define the protocol buffer field numbers;
// they follow the convention outlined by the reflect package.
struct {
microsec uint64 protobuf:"1"
serverIP6 uint64 protobuf:"2"
}
A real example
A common use case is when unmarshalling JSON, as I did inUse Go for JSON processing.
In that article, this example
type Member struct {
Age int `json:"age,string"`
}
telljson.Unmarshal()
Putage
JSON attributes, onestring
And place it inAge
on siteMember
,translate toint
. In this example, we passjson
Two pieces of information, separated by commas.
Label format
Label usekey:"value"
format. This is not a strict rule, but a convention to provide built-in resolution. In this example, we only have one key-value pair, but we can have more than one:
type Member struct {
Age int `json:"age,string" xml:"the_age,string"`
}
By convention, the key is the name of the package we want to locate. In the example above,encoding/json
withencoding/xml
.
But tags can also be used by ourselves in our own libraries, they are not only reserved for the standard library.
What is the use of labels?
Different software packages use tags for different reasons.
You will see that they are used in encoding libraries, such as json, xml, bson, yaml, and also in ORM/database libraries, and evenFill the structure with form data.
The following list was posted onand soAnd very comprehensive:
json
-byencoding/json
Packing, detailed descriptionjson.Marshal()
xml
-byencoding/xml
Packing, detailed descriptionxml.Marshal()
bson
-byCobson, Seebson.Marshal()
protobuf
-bygithub.com/golang/protobuf/proto
, There are detailed instructions in the packaging documentyaml
-bygopkg.in/yaml.v2
Packing, detailed descriptionyaml.Marshal()
db
-bygithub.com/jmoiron/sqlx
packageorm
-bygithub.com/astaxie/beego/orm
Packing, detailed descriptionModel-Beego ORMgorm
-bygithub.com/jinzhu/gorm
Package, examples can be found in its documentation:Modeldatastore
-byappengine/datastore
(Data storage service of Google App Engine platform), please refer tocharacteristicschema
-bygithub.com/gorilla/schema
Fill instruct
With HTML form values (detailed in the package documentation)asn
-byencoding/asn1
Packing, detailed descriptionasn1.Marshal()
withasn1.Unmarshal()
There are many other uses in the wild. E.gmcuadros / go-defaultsUse it to set default values for structure fields, andasaskevich / govalidatorAllows to add tags that confirm verification (this is just one possible method of verification,Alternatives exist).
fatih/gomodifytagsAllow editing of tags at runtime,
Use tags in code
To use tags in your own code, you can usereflect
package.
Let's tryage
In the member structure. The following code
package main
import (
“fmt”
“reflect”
)
type Member struct {
Age int something:"age"
}
func main() {
member := Member{34}
t := reflect.TypeOf(member)
field := t.Field(0)
//field, _ := t.FieldByName(“Age”) //alternative
fmt.Print(field.Tag.Get(“something”))
}
Will printage
, Thanks tokey:"value"
The format of the label.
More tutorials:
- Use NGINX reverse proxy service Go service
- Copy structure in Go
- Basics of Go web server
- Sorting map types in Go
- In a nutshell
- Go to label description
- Start date and time format
- Use Go for JSON processing
- Variadic function
- Cheat sheet
- Go to the empty interface description
- Use VS Code and Delve to debug Go
- Named Go return parameter
- Generate random numbers and strings in Go
- File system structure of Go project
- Binary search algorithm in Go
- Use command line flags in Go
- GOPATH explained
- Use Go to build a command line application: lolcat
- Use Go to build CLI commands: Cowsay
- Use shell and tube in Go
- Go CLI Tutorial: Fortune Clone
- Use Go to list files in a folder
- Use Go to get a list of repositories from GitHub
- Go, append a short string to the file
- Go, convert the string to byte slices
- Use Go to visualize your local Git contributions
- Getting started with Go CPU and memory analysis
- Solve the "Does not support index" error in the Go program
- Measuring the execution time in the Go program
- Use Go to build a web crawler to detect duplicate titles
- Best Practice: Pointer or Value Receiver?
- Best practice: Should you use methods or functions?
- Go data structure: set
- Go to the map cheat sheet
- Generating the implementation of generic types in Go
- Go data structure: dictionary
- Go data structure: hash table
- Implement event listeners in "through the channel"
- Go data structure: stack
- Go data structure: queue
- Go data structure: binary search tree
- Go data structure: graphics
- Go data structure: linked list
- A complete guide to Go data structures
- Compare Go value
- Is Go object-oriented?
- Use SQL database in Go
- Use environment variables in Go
- Last tutorial: REST API supported by PostgreSQL
- Enable CORS on the Go web server
- Deploy Go application in Docker container
- Why Go is a powerful language to learn as a PHP developer
- Go and delete the io.Reader.ReadString newline
- To start, how to watch the changes and rebuild the program
- To count the months since the date
- Access HTTP POST parameters in Go