How do I reverse an arbitrary slice ([]interface{}
) in Go? I'd rather not have to write Less
and Swap
to use sort.Reverse
. Is there a simple, builtin way to do this?
Approach to solve this problemStep 1: Define a function that accepts an array. Step 2: Start iterating the input array. Step 3: Swap first element with last element of the given array. Step 4: Return array.
Step 1 − Define a method that accepts the head of a linked list. Step 2 − If head == nil, return; else, call ReverseLinkedList, recursively. Step 3 − Print head. value at the end.
The standard library does not have a built-in function for reversing a slice. Use a for loop to reverse a slice:
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] }
Use type parameters to write a generic reverse function in Go 1.18 or later:
func reverse[S ~[]E, E any](s S) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } }
Use reflect.Swapper to write a function that works with arbitrary slice types in Go version 1.8 or later:
func reverse(s interface{}) { n := reflect.ValueOf(s).Len() swap := reflect.Swapper(s) for i, j := 0, n-1; i < j; i, j = i+1, j-1 { swap(i, j) } }
Run the code on the Go playground.
The functions in this answer reverse the slice inplace. If you do not want to modify the original slice, copy the slice before reversing the slice.
This will return a reversed slice without modifying the original slice.
Algorithm used from official wiki page: https://github.com/golang/go/wiki/SliceTricks#reversing
func reverse(s []interface{}) []interface{} { a := make([]interface{}, len(s)) copy(a, s) for i := len(a)/2 - 1; i >= 0; i-- { opp := len(a) - 1 - i a[i], a[opp] = a[opp], a[i] } return a }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With