Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reverse a slice in go?

Tags:

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?

like image 552
Andrew C Avatar asked Jan 21 '15 01:01

Andrew C


People also ask

How do you reverse an array in go?

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.

How do you reverse a linked list in Golang?

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.


2 Answers

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.

like image 151
Bayta Darell Avatar answered Oct 31 '22 18:10

Bayta Darell


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 } 
like image 35
mzarrugh Avatar answered Oct 31 '22 20:10

mzarrugh