Golang : Struct field tags and what is their purpose?
Got a curious question asked by a colleague today on what's the purpose on field tags inside a struct. For the uninitiated, field tags look like this :
type Employee struct {
Name string `json:"name" xml:"name"`
Age int `json:"age,omitempty" xml:"age,omitempty"`
}
the [json:"name" xml:"name"] is what a Golang programmer refer to field tags.
Basically, it is a form of meta-data that instruct your software on how to handle data fields inside the structure during compile-time or runtime. For the example code above, the instruction is to map the Name and Age data fields to their equivalent field names should the program generate JSON or XML files. The tag instruction omitempty
instruct the JSON or XML code generated to ignore the empty data fields should the Age field is empty.
Apart from the most common field tags for JSON and XML. You may encounter the schema
field tags use by http://godoc.org/github.com/gorilla/schema or the datastore
field tags - used by Google App Engine.
See also : Golang : When to use init() function?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.6k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+36.6k Golang : How to split or chunking a file to smaller pieces?
+16.5k Golang : Loop each day of the current month example
+5.3k Golang : Calculate half life decay example
+20.6k Golang : Pipe output from one os.Exec(shell command) to another command
+6k AWS S3 : Prevent Hotlinking policy
+6.3k Golang & Javascript : How to save cropped image to file on server
+9.9k Golang : Resumable upload to Google Drive(RESTful) example
+5.7k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+6.1k Golang : Extract unicode string from another unicode string example
+9.1k Golang : automatically figure out array length(size) with three dots
+14.8k Golang : Reset buffer example