Write a structure with labels
type server struct{ XMLName 'xml:"server"' }
solve
Compilation error field tag must be a string. Later I found that the quotes on the subsequent tag were incorrect. It should not be a single quote next to the Enter key, but a single quote next to the numeric key 1.
type server struct{ XMLName `xml:"server"` }
Supplement: Tag description and acquisition method of struct member variable in golang
When processing json format strings, you often see that when declaring struct structure, there is also content enclosed by Xiaomi on the right side of the property. As shown in:
type User struct { UserId int `json:"user_id" bson:"user_id"` UserName string `json:"user_name" bson:"user_name"` }
What is the content in this Xiaomi dot used for?
struct member variable tag (Tag) description
To understand this in more detail, you must first understand the basics of golang. In golang, naming is recommended in camel method, and has a special syntax meaning in the upper and lower case of the first letter: it cannot be quoted outside the package.
However, data interaction is often required with other systems, such as converting it to JSON format, storing it to mongodb, etc.
At this time, if you use the attribute name as the key value, it may not necessarily meet the project requirements.
So there is more content of Xiaomi dots, which is called tags in golang. When converted to other data formats, specific fields will be used as key values.
For example, the above example is converted to json format:
u := &User{UserId: 1, UserName: "tony"} j, _ := (u) (string(j)) // Output content: {"user_id":1,"user_name":"tony"}
If no tag description is added to the attribute, the output is:
{"UserId":1,"UserName":"tony"}
You can see that the key value is directly used as the attribute name of struct.
There is also a Bson statement, which is used to store data to mongodb.
struct member variable tag (Tag) get
So when we need to encapsulate some operations ourselves and use the content in the tag, how to obtain it? Here you can use the method in the reflection package (reflect) to obtain:
t := (u) field := ().Field(0) (("json")) (("bson"))
The complete code is as follows:
package main import ( "encoding/json" "fmt" "reflect" ) func main() { type User struct { UserId int `json:"user_id" bson:"user_id"` UserName string `json:"user_name" bson:"user_name"` } // Output json format u := &User{UserId: 1, UserName: "tony"} j, _ := (u) (string(j)) // Output content: {"user_id":1,"user_name":"tony"} // Get the content in the tag t := (u) field := ().Field(0) (("json")) // Output: user_id (("bson")) // Output: user_id}
The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.