How to get struct variable information using reflect package?
Using reflect package you can also find the name and type of struct variables.
Example
package main
import (
"fmt"
"reflect"
)
type Book struct {
Id int
Title string
Price float32
Authors []string
}
func main() {
book := Book{}
e := reflect.ValueOf(&book).Elem()
for i := 0; i < e.NumField(); i++ {
varName := e.Type().Field(i).Name
varType := e.Type().Field(i).Type
varValue := e.Field(i).Interface()
fmt.Printf("%v %v %v\n", varName,varType,varValue)
}
}
Output
Id int 0
Title string
Price float32 0
Authors []string []
Most Helpful This Week
How to wait for Goroutines to Finish Execution?
How can we reverse a simple string in Go?
How do you write multi-line strings in Go?
Encoding and Decoding using json.Marshal and json.Unmarshal
Regular expression to extract all Non-Alphanumeric Characters from a String
Subtract N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-time.