-
-
Save justincase/5469009 to your computer and use it in GitHub Desktop.
type T struct { | |
A int | |
B string | |
} | |
t := T{23, "skidoo"} | |
s := reflect.ValueOf(&t).Elem() | |
typeOfT := s.Type() | |
for i := 0; i < s.NumField(); i++ { | |
f := s.Field(i) | |
fmt.Printf("%d: %s %s = %v\n", i, | |
typeOfT.Field(i).Name, f.Type(), f.Interface()) | |
} | |
// The output of this program is | |
// | |
// 0: A int = 23 | |
// 1: B string = skidoo |
well played, thank you :)
thank you :)
panic: reflect: call of reflect.Value.NumField on interface Value
It gives me this error.
My struct is defined as :
type bundle struct {
valnode *Node
tree *tree
}
awesome guy!
Excellent - Clean, succinct
Spent several hours before finding this Thanks
f.Interface undefined..
@xgz123 you're probably calling reflect.TypeOf(struct)
rather than reflect.ValueOf(struct)
. Calling Field(i)
on a Type
returns a StructField
which doesn't have the Interface
method. Calling reflect.ValueOf(struct).Field(i)
returns a Value
which does have the Interface
method.
f.Interface()
only works for the struct
type which has public fields.
This code worked.
v := reflect.ValueOf(structValue)
t := v.Type()
for i := 0; i < t.NumField(); i++ {
name := t.Field(i).Name
value := v.FieldByName(name).Interface()
}
@mrdulin just put in a guard to check f.PkgPath, since it's only populated for unexported fields, f.PkgPath == ""
will only be true for exported fields, so you can avoid panics when trying to process unexported fields.
Nice explanatory code for extracting the details of structure's field name, its value and type.