var Reverse = func(slice interface{}) {
s := reflect.ValueOf(slice)
// if s is a pointer of slice
if s.Kind() == reflect.Ptr {
s = s.Elem()
}
i := 0
j := s.Len() - 1
for i < j {
x, y := s.Index(i).Interface(),
s.Index(j).Interface()
s.Index(i).Set(reflect.ValueOf(y))
s.Index(j).Set(reflect.ValueOf(x))
i++
j--
}
}
I found this way works.But it is not elegant.... I know there is a method "Swapper" in reflect package. But I don't know how to make it work if the argument of above function is a pointer of slice.
Really appreciate.
Your code works fine. To use reflect.Swapper
, just pass s.Interface()
into it:
var Reverse = func(slice interface{}) {
s := reflect.ValueOf(slice)
// if s is a pointer of slice
if s.Kind() == reflect.Ptr {
s = s.Elem()
}
swp := reflect.Swapper(s.Interface())
for i,j :=0,s.Len() - 1; i<j; i,j = i+1,j-1 {
swp(i,j)
}
}
Playground: https://play.golang.org/p/DSq_iZRZX4b