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
+86k Golang : How to convert character to ASCII and back
+8.9k Golang : Gonum standard normal random numbers example
+7.8k How to show different content from website server when AdBlock is detected?
+11k Golang : How to use if, eq and print properly in html template
+5.7k Golang : Use NLP to get sentences for each paragraph example
+4.7k Google : Block or disable caching of your website content
+6.8k Golang : Takes a plural word and makes it singular
+20.5k Golang : Convert PNG transparent background image to JPG or JPEG image
+12.4k Swift : Convert (cast) Int or int32 value to CGFloat
+12.1k Elastic Search : Return all records (higher than default 10)
+5.1k Golang : Get FX sentiment from website example
+9.7k Golang : Setting variable value with ldflags