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
+16.5k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+20.2k Android Studio : AlertDialog and EditText to get user string input example
+20.2k Golang : Pipe output from one os.Exec(shell command) to another command
+25k Golang : Get current file path of a file or executable
+8.6k Golang : Accept any number of function arguments with three dots(...)
+7.3k Gogland : Single File versus Go Application Run Configurations
+19.6k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+40.7k Golang : How to check if a string contains another sub-string?
+10.5k Golang : Underscore string example
+9k Golang : How to check if a string with spaces in between is numeric?
+16.1k Golang :Trim white spaces from a string
+6.4k Elasticsearch : Shutdown a local node