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
+39.3k Golang : Remove dashes(or any character) from string
+16.8k Golang : How to save log messages to file?
+4.2k Linux/MacOSX : Search and delete files by extension
+4.8k Google : Block or disable caching of your website content
+15.3k Golang : Force download file example
+7.1k Golang : alternative to os.Exit() function
+16.6k Golang : Set up source IP address before making HTTP request
+19.8k Golang : Compare floating-point numbers
+7.1k Golang : File system scanning
+14.8k Golang : package is not in GOROOT during compilation
+5k PHP : See installed compiled-in-modules
+5.2k Golang *File points to a file or directory ?