How to get struct variable information using reflect package?
Using reflect package you can also find the name and type of and value of struct variables.
package main
import (
"fmt"
"reflect"
)
type Book struct {
Id int
Title string
Price float32
Authors []string
}
func main() {
book := Book{1, "foo", 1.5, []string{"alex"}}
e := reflect.Indirect(reflect.ValueOf(&book))
for i := 0; i < e.NumField(); i++ {
varName := e.Type().Field(i).Name
varType := e.Field(i).Type
varValue := e.Field(i).Interface()
fmt.Printf("%v %v %v\n", varName,varType,varValue)
}
}
Written by azbshiri
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Go
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#