Golang : What is StructTag and how to get StructTag's value?
For those who code or read Golang's code and left wondering what are those string inside the '``'
such as xml:"firstname"
Such as these example below :
type Staff struct {
XMLName xml.Name `xml:"staff"`
ID int `xml:"id"`
FirstName string `xml:"firstname"`
LastName string `xml:"lastname"`
UserName string `xml:"username"`
}
type Company struct {
XMLName xml.Name `xml:"company"`
Staffs []Staff `xml:"staff"`
}
They are known as StructTag and you can process the tags with the reflect
package. In this example, we will extract the custom tags' value with field.Tag.Get()
method :
package main
import (
"encoding/xml"
"fmt"
"reflect"
)
func main() {
type Company struct {
XMLName xml.Name `xml:"company"`
}
c := Company{}
cType := reflect.TypeOf(c)
field := cType.Field(0)
xmlTag := field.Tag.Get("xml")
fmt.Println(xmlTag)
type S struct {
F string `species:"gopher" color:"pink"`
}
s := S{}
st := reflect.TypeOf(s)
field = st.Field(0)
fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
}
Output :
company
pink gopher
One usage example that I can think of is that StructTag allows a developer to create her/his own custom tagging and use the tags to find the relevant field and extract value from the field.
Hope this short tutorials can be useful to you!
Reference :
See also : Golang : How to get struct field and value by name
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
+6.7k Golang : Humanize and Titleize functions
+8.9k Golang : Populate or initialize struct with values example
+14.3k Golang : Parsing or breaking down URL
+14.5k Golang : Reset buffer example
+9.3k Golang : How to protect your source code from client, hosting company or hacker?
+5.5k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+19.2k Golang : Calculate entire request body length during run time
+6.2k Golang : Process non-XML/JSON formatted ASCII text file example
+5k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+9.9k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+6.3k Golang : Test input string for unicode example
+8k Golang : Check from web if Go application is running or not