Reflection in go!
Printing struct attributes and values using reflection.
package main
import (
"fmt"
"reflect"
)
type User struct {
FirstName string
LastName string
Age int
}
func (f *User) reflect() {
v := reflect.ValueOf(f).Elem()
for i := 0; i < v.NumField(); i++ {
val := v.Field(i)
t := v.Type().Field(i)
fmt.Printf("%s %v \t", t.Name, val.Interface())
}
}
func main() {
f := &User{
FirstName: "John",
LastName: "Doe",
Age: 13,
}
f.reflect()
}