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
+22.5k Golang : Convert Unix timestamp to UTC timestamp
+10.7k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+13k Swift : Convert (cast) Int to String ?
+8.3k Golang : Qt splash screen with delay example
+24.6k Golang : GORM read from database example
+10.6k Golang : Create matrix with Gonum Matrix package example
+21.1k Golang : Sort and reverse sort a slice of strings
+22.8k Golang : Set and Get HTTP request headers example
+7.5k Golang : How to detect if a sentence ends with a punctuation?
+10.4k Golang : How to check if a website is served via HTTPS
+6.8k Golang : Calculate pivot points for a cross
+13.2k Golang : Handle or parse date string with Z suffix(RFC3339) example