Golang : How to get struct tag and use field name to retrieve data?
Problem :
A structure data field can have additional information or meta-data. This information is known as struct tag in Golang. You want to find out a struct data field type's struct tag. How to that with the reflect
package?
NOTE : Don't confuse field name and struct tag yeah!
Solution :
Use the reflect package StructField type to retrieve the data.
Here you go !
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string `json:name`
}
func getStructTag(f reflect.StructField) string {
return string(f.Tag)
}
func main() {
user := &Person{"Adam"}
field, ok := reflect.TypeOf(user).Elem().FieldByName("Name") // not json:name
if !ok {
panic("Field not found")
}
// get the struct field tag
// see http://golang.org/pkg/reflect/#StructField
fmt.Println(getStructTag(field)) // json:name
//----- get data from the initialized Person struct
//----- based on the field name
r := reflect.ValueOf(user)
f := reflect.Indirect(r).FieldByName("Name")
fmt.Println(f)
}
Output :
json:name
Adam
Happy coding !
References :
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
+12.3k Golang : HTTP response JSON encoded data
+14.1k Golang : On enumeration
+4.6k Javascript : How to get width and height of a div?
+11.3k Golang : Fuzzy string search or approximate string matching example
+30.5k Golang : Interpolating or substituting variables in string examples
+18.4k Golang : convert int to string
+26k Golang : Calculate future date with time.Add() function
+8.6k Golang : Populate or initialize struct with values example
+4.5k Fix Google Analytics Redundant Hostnames problem
+4.5k Unix/Linux : How to pipe/save output of a command to file?
+35.4k Golang : Get file last modified date and time
+9.7k Golang : Channels and buffered channels examples