How to reverse an array in Golang?

by raul_reichert , in category: Golang , 2 years ago

How to reverse an array in Golang?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by emely , 2 years ago

@raul_reichert You can use for loop and iterate over the elements and reverse an array in Golang, here is code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import "fmt"

func main() {
   arr := []int{5, 4, 3, 2, 1}
   var reverse []int

   for i := len(arr) - 1; i >= 0; i-- {
      reverse = append(reverse, arr[i])
   }

   // Output: [1 2 3 4 5]
   fmt.Println(reverse)
}


by edison.lang , a year ago

@raul_reichert 

In Go, you can reverse an array by swapping its elements. Here's an example of how to do it:

1
2
3
4
5
func reverseArray(arr []int) {
    for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {
        arr[i], arr[j] = arr[j], arr[i]
    }
}


Here, we're using a for loop to swap the first and last elements, the second and second-to-last elements, and so on until we've swapped all the elements. We're using two variables, i and j, to keep track of the indices of the elements we're swapping. We're also using a slice of integers as the input array, but this code should work for any type of array.


To use this function, simply call it with your array as the argument:

1
2
3
arr := []int{1, 2, 3, 4, 5}
reverseArray(arr)
fmt.Println(arr) // [5, 4, 3, 2, 1]


This code will print the reversed array [5, 4, 3, 2, 1].