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
+19.2k Golang : Pipe output from one os.Exec(shell command) to another command
+9.6k Golang : How to transmit update file to client by HTTP request example
+15.7k Golang : How to tell if a file is compressed either gzip or zip ?
+19.8k Golang : For loop continue,break and range
+7.6k Golang : How to join strings?
+4.3k JavaScript/JQuery : Redirect page examples
+44.6k Golang : Encode image to base64 example
+18.6k Android Studio : AlertDialog and EditText to get user string input example
+11.7k Golang : http.Get example
+18.2k Golang : How to run your code only once with sync.Once object
+18.3k Golang : Compare floating-point numbers
+10.5k Golang : flag provided but not defined error