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
+5.6k Javascript : How to refresh page with JQuery ?
+4k Detect if Google Analytics and Developer Media are loaded properly or not
+5.4k Golang : Reclaim memory occupied by make() example
+21.5k Golang : How to read float value from standard input ?
+5.9k Golang : Use NLP to get sentences for each paragraph example
+6.3k Golang : Test input string for unicode example
+6.9k How to let Facebook Login button redirect to a particular URL ?
+21.8k SSL : How to check if current certificate is sha1 or sha2
+12.3k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+11.7k Golang : Find age or leap age from date of birth example
+5.6k Golang : Detect words using using consecutive letters in a given string
+20.6k Nginx + FastCGI + Go Setup.