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
+7.2k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+8k CodeIgniter : Load different view for mobile devices
+6.4k Golang : How to use if, eq and print properly in html template
+5.6k Android Studio : Import third-party library or package into Gradle Scripts
+2.6k MariaDB/MySQL : How to get version information
+13.1k Golang : Capture stdout of a child process and act according to the result
+18.8k Golang : Daemonizing a simple web server process example
+11.9k Golang : convert string or integer to big.Int type
+7.7k Javascript : Read/parse JSON data from HTTP response
+3k JavaScript/JQuery : Redirect page examples
+3.5k Python : Delay with time.sleep() function example
+19.6k Golang : dial tcp: too many colons in address