Hi, the title is probably not very self explanatory.
I’m trying to create a generic function that accept any kind of struct, loops through its fields and displays its values
The problem is for a struct like
type Some struct {
Name string
Birth *strfmt.DateTime
Value *int64
}
My function returns the correct values for Name and Birth but not for Value
The function:
func someThing(data interface{}) {
ref := reflect.ValueOf(data)
for i := 0; i < ref.NumField(); i++ {
prop := ref.Type().Field(i).Name
val := fmt.Sprintf("%v", ref.Field(i).Interface())
valType := fmt.Sprintf("%T", ref.Field(i).Interface())
rawValue := ref.Field(i).Interface()
fmt.Println(prop, val, valType, rawValue)
}
}
This returns for example:
Name me string me
Birth 2009-11-10T23:00:00.000Z *strfmt.DateTime 2009-11-10T23:00:00.000Z <---- value here
Value 0xa80f68 *int64 0xa80f68 <---- address here
Full code on the playground: https://play.golang.org/p/RAQ8HLOCUB2
(external import from github can be capricious, try to click format and run again)
Note: The final goal of this function is to append keys and values to slices and return them
var props []string
var vals []interface{}