I have a function which accept all type of struct as interface. If I try to print
s.Index(i)
It gives me the values. However once I append it into
allRows []interface{}
and print it out. Instead of value I am getting the type of struct that I passed the function. As an exapmle.
fmt.Println("AllRows",allRows)
[<adminPanel.allBeaconInfo Value> <adminPanel.allBeaconInfo Value> <adminPanel.allBeaconInfo Value> <adminPanel.allBeaconInfo Value> <adminPanel.allBeaconInfo Value>]
func pagination(c *gin.Context, st interface{}) {
var allRows []interface{}
switch reflect.TypeOf(st).Kind() {
case reflect.Slice:
s := reflect.ValueOf(st)
for i := 0; i < s.Len(); i {
allRows=append(allRows,s.Index(i))
fmt.Println(allRows)
}
}
fmt.Println("AllRows",allRows)
CodePudding user response:
The expression s.Index(i)
evaluates to a reflect.Value
containing the actual slice element. Call Value.Interface() to get the actual slice element.
var allRows []interface{}
switch reflect.TypeOf(st).Kind() {
case reflect.Slice:
s := reflect.ValueOf(st)
for i := 0; i < s.Len(); i {
allRows=append(allRows,s.Index(i).Interface())
fmt.Println(allRows)
}
}