How to reverse the order of elements in a slice in Golang?

To reverse the order of elements in a slice in Go, you can use a simple loop to swap elements starting from both ends until the middle is reached. Here's an example:

package main import "fmt" func reverseSlice(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func main() { slice := []int{1, 2, 3, 4, 5} fmt.Println(slice) // original slice: [1 2 3 4 5] reverseSlice(slice) fmt.Println(slice) // reversed slice: [5 4 3 2 1] }

In the reverseSlice function, we iterate over the slice using two pointers, one starting from the beginning (i) and the other starting from the end (j). In each iteration, we swap the elements at positions i and j using a parallel assignment. The loop continues until i reaches j, effectively reversing the order of elements in the slice.

If you want to reverse the order of elements in a string slice or any other type of slice, you can simply change the type of the slice and elements accordingly.