Reflection - pointer to int64 is not dereferenced but pointer to date is

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{}

Interface method return type is ptr in Some.Value or Some.Birth field,must reflect Indiect or Elem get that the pointer points to val.
reflect.Indirect func return zero or multiple ptr points to val.
reflect.Value.Elem method retun once points to val,it panic if Value Kind not is Interface or Ptr.

		rawValue := reflect.Indirect(ref.Field(i)).Interface()
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.