Golang : How to get struct field and value by name
In Go, there are times when we need to find out the value of a field in a given structure base on the name of the field. This tutorial will show how to use the reflect
package to find out the associated value from the field name.
package main
import (
"fmt"
"reflect"
)
type Employee struct {
Name string
Age int
Job string
}
func getFieldString(e *Employee, field string) string {
r := reflect.ValueOf(e)
f := reflect.Indirect(r).FieldByName(field)
return f.String()
}
func getFieldInteger(e *Employee, field string) int {
r := reflect.ValueOf(e)
f := reflect.Indirect(r).FieldByName(field)
return int(f.Int())
}
func main() {
e := Employee{"Adam", 36, "CEO"}
fmt.Println(getFieldString(&e, "Name"))
fmt.Println(getFieldInteger(&e, "Age"))
fmt.Println(getFieldString(&e, "Job"))
}
Output :
Adam
36
CEO
Recommended reading on how to use reflect :
http://blog.golang.org/laws-of-reflection
References :
https://www.socketloop.com/tutorials/golang-print-out-struct-values-in-string-format
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
+6k AWS S3 : Prevent Hotlinking policy
+9.4k Golang : How to get garbage collection data?
+8.4k Golang : Add build version and other information in executables
+26.6k Golang : Convert(cast) string to uint8 type and back to string
+7.2k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+7.9k Golang : Generate human readable password
+11.8k Golang : Calculations using complex numbers example
+12.4k Golang : Get month name from date example
+8.2k Golang : Tell color name with OpenCV example
+14.1k Golang : How to determine if a year is leap year?
+7.2k Golang : Squaring elements in array
+46.4k Golang : Read tab delimited file with encoding/csv package